From d47322e73bab8d0c2b10bd150fc499fd5773607a Mon Sep 17 00:00:00 2001 From: kazu Date: Wed, 28 Sep 2016 12:16:45 +0200 Subject: [PATCH] current revision --- Config.h | 29 - Controller.cpp | 145 +- Controller.h | 23 +- Settings.h | 83 +- Stairs.h | 4 - _android/src/MyActivity.java | 8 + _android/src/StepLoggerClient.java | 79 + _android/src/WiFi.java | 4 +- .../isti/steplogger/IStepLoggerService.aidl | 8 + ipin/Config.h | 104 + ipin/IPINHelper.h | 22 + ipin/Scaler.h | 104 + ipin/StepLogger.h | 188 ++ ipin/StepLoggerWrapper.h | 97 + ipin/StepLoggerWrapperAndroid.h | 61 + lib/tinyxml/tinyxml2.cpp | 2467 +++++++++++++++++ lib/tinyxml/tinyxml2.h | 2102 ++++++++++++++ main.cpp | 68 +- nav/Filter.h | 150 +- nav/NavController.h | 291 +- nav/NavControllerListener.h | 15 + nav/Node.h | 10 +- nav/NodeResampling.h | 123 + nav/State.h | 12 +- qml.qrc | 2 + res/gl/fragmentColorPoint.glsl | 2 +- res/gl/fragmentTex.glsl | 7 +- res/icons/dots.svg | 73 + res/icons/wall.svg | 54 + sensors/ActivitySensor.h | 63 + sensors/Sensor.h | 8 + sensors/SensorFactory.h | 8 +- sensors/StepSensor.h | 11 +- sensors/TurnSensor.h | 14 +- sensors/android/AccelerometerSensorAndroid.h | 4 + sensors/android/BarometerSensorAndroid.h | 6 +- sensors/android/GyroscopeSensorAndroid.h | 4 + sensors/android/WiFiSensorAndroid.cpp | 3 +- sensors/android/WiFiSensorAndroid.h | 11 +- sensors/dummy/RandomSensor.h | 5 + sensors/dummy/WiFiSensorDummy.h | 3 + sensors/offline/AllInOneSensor.h | 4 + tests/RuntimeTests.h | 58 + tools/calibration/WiFiCalibrationDataModel.h | 92 + .../calibration/WiFiCalibrationScanDialog.cpp | 51 + tools/calibration/WiFiCalibrationScanDialog.h | 102 + ui/LoggerUI.h | 46 + ui/MainWindow.cpp | 41 +- ui/MainWindow.h | 20 +- ui/UIHelper.h | 39 + ui/debug/InfoWidget.cpp | 67 + ui/debug/InfoWidget.h | 35 + ui/debug/PlotTurns.cpp | 4 +- ui/debug/PlotTurns.h | 2 + ui/debug/PlotWiFiScan.cpp | 14 +- ui/debug/SensorDataWidget.cpp | 102 +- ui/debug/SensorDataWidget.h | 7 + ui/dialog/LoadSetupDialog.cpp | 6 +- ui/map/2D/ColorPoints2D.h | 120 + ui/map/2D/Floor2D.h | 62 + ui/map/2D/HasSelectableNodes.h | 20 + ui/map/2D/MapView2D.cpp | 184 ++ ui/map/2D/MapView2D.h | 131 + ui/map/2D/Path2D.h | 123 + ui/map/2D/RenderParams2D.h | 13 + ui/map/2D/Renderable2D.h | 37 + ui/map/2D/Scaler2D.h | 106 + ui/map/2D/WiFiCalibTool.h | 129 + ui/map/{ => 3D}/FloorRenderer.h | 0 ui/map/{MapView.cpp => 3D/MapView3D.cpp} | 154 +- ui/map/{MapView.h => 3D/MapView3D.h} | 55 +- ui/map/3D/RenderParams.h | 11 + ui/map/{ => 3D}/Renderable.h | 11 +- ui/map/{ => 3D}/elements/ColorPoints.h | 41 +- ui/map/{ => 3D}/elements/Doors.h | 7 +- ui/map/{ => 3D}/elements/Ground.h | 26 +- ui/map/{ => 3D}/elements/Handrails.h | 3 +- ui/map/{ => 3D}/elements/Object.h | 3 +- ui/map/{ => 3D}/elements/Path.h | 199 +- ui/map/{ => 3D}/elements/Stairs.h | 3 +- ui/map/{ => 3D}/elements/Walls.h | 25 +- ui/map/{ => 3D}/gl/GL.h | 17 +- ui/map/{ => 3D}/gl/GLHelper.h | 0 ui/map/{ => 3D}/gl/GLLines.h | 0 ui/map/{ => 3D}/gl/GLPoints.h | 31 +- ui/map/{ => 3D}/gl/GLTriangles.h | 29 +- ui/map/{ => 3D}/gl/Shader.h | 0 ui/menu/MainMenu.cpp | 41 +- ui/menu/MainMenu.h | 8 + yasmin.pro | 80 +- 90 files changed, 8228 insertions(+), 606 deletions(-) delete mode 100644 Config.h delete mode 100644 Stairs.h create mode 100644 _android/src/StepLoggerClient.java create mode 100644 _android/src/aidl/it/cnr/isti/steplogger/IStepLoggerService.aidl create mode 100644 ipin/Config.h create mode 100644 ipin/IPINHelper.h create mode 100644 ipin/Scaler.h create mode 100644 ipin/StepLogger.h create mode 100644 ipin/StepLoggerWrapper.h create mode 100644 ipin/StepLoggerWrapperAndroid.h create mode 100644 lib/tinyxml/tinyxml2.cpp create mode 100644 lib/tinyxml/tinyxml2.h create mode 100644 nav/NavControllerListener.h create mode 100644 nav/NodeResampling.h create mode 100644 res/icons/dots.svg create mode 100644 res/icons/wall.svg create mode 100644 sensors/ActivitySensor.h create mode 100644 tests/RuntimeTests.h create mode 100644 tools/calibration/WiFiCalibrationDataModel.h create mode 100644 tools/calibration/WiFiCalibrationScanDialog.cpp create mode 100644 tools/calibration/WiFiCalibrationScanDialog.h create mode 100644 ui/LoggerUI.h create mode 100644 ui/UIHelper.h create mode 100644 ui/debug/InfoWidget.cpp create mode 100644 ui/debug/InfoWidget.h create mode 100644 ui/map/2D/ColorPoints2D.h create mode 100644 ui/map/2D/Floor2D.h create mode 100644 ui/map/2D/HasSelectableNodes.h create mode 100644 ui/map/2D/MapView2D.cpp create mode 100644 ui/map/2D/MapView2D.h create mode 100644 ui/map/2D/Path2D.h create mode 100644 ui/map/2D/RenderParams2D.h create mode 100644 ui/map/2D/Renderable2D.h create mode 100644 ui/map/2D/Scaler2D.h create mode 100644 ui/map/2D/WiFiCalibTool.h rename ui/map/{ => 3D}/FloorRenderer.h (100%) rename ui/map/{MapView.cpp => 3D/MapView3D.cpp} (53%) rename ui/map/{MapView.h => 3D/MapView3D.h} (63%) create mode 100644 ui/map/3D/RenderParams.h rename ui/map/{ => 3D}/Renderable.h (84%) rename ui/map/{ => 3D}/elements/ColorPoints.h (70%) rename ui/map/{ => 3D}/elements/Doors.h (94%) rename ui/map/{ => 3D}/elements/Ground.h (87%) rename ui/map/{ => 3D}/elements/Handrails.h (93%) rename ui/map/{ => 3D}/elements/Object.h (96%) rename ui/map/{ => 3D}/elements/Path.h (53%) rename ui/map/{ => 3D}/elements/Stairs.h (98%) rename ui/map/{ => 3D}/elements/Walls.h (88%) rename ui/map/{ => 3D}/gl/GL.h (77%) rename ui/map/{ => 3D}/gl/GLHelper.h (100%) rename ui/map/{ => 3D}/gl/GLLines.h (100%) rename ui/map/{ => 3D}/gl/GLPoints.h (74%) rename ui/map/{ => 3D}/gl/GLTriangles.h (83%) rename ui/map/{ => 3D}/gl/Shader.h (100%) diff --git a/Config.h b/Config.h deleted file mode 100644 index 82a65ec..0000000 --- a/Config.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef CONFIG_H -#define CONFIG_H - -#include -#include - -class Config { - -public: - - // notes - // copy: scp -P 2222 /tmp/grid.dat kazu@192.168.24.11:/storage/sdcard1/YASMIN/maps/car/ - // all: scp -P 2222 -r /apps/android/workspace/YASMIN_DATA/* kazu@192.168.24.11:/storage/sdcard1/YASMIN/ - - /** get the directory where maps are stored */ - static inline std::string getMapDir() { -#ifdef ANDROID -// const std::string folder = getenv("EXTERNAL_STORAGE") + std::string("/YASMIN/maps/"); // this is NOT the sdcard?! -// qDebug(folder.c_str()); -// return folder; - return "/storage/sdcard1/YASMIN/maps/"; -#else - return "/apps/android/workspace/YASMIN_DATA/maps/"; -#endif - } - -}; - -#endif // CONFIG_H diff --git a/Controller.cpp b/Controller.cpp index cbf52b1..2541e39 100644 --- a/Controller.cpp +++ b/Controller.cpp @@ -1,6 +1,8 @@ #include "Controller.h" -#include "ui/map/MapView.h" +#include "ui/map/3D/MapView3D.h" +#include "ui/map/2D/MapView2D.h" + #include "ui/menu/MainMenu.h" #include "ui/MainWindow.h" #include "ui/dialog/LoadSetupDialog.h" @@ -11,15 +13,27 @@ #include #include +#include + +#include + #include +#include "ui/LoggerUI.h" +#include +#include +#include + + #include "sensors/dummy/SensorFactoryDummy.h" #include "sensors/android/SensorFactoryAndroid.h" #include "sensors/offline/SensorFactoryOffline.h" +#include "tools/calibration/WiFiCalibrationDataModel.h" + #include "nav/NavController.h" -Controller::Controller() { +Controller::Controller() : sl(scaler) { // OpenGL setup // MUST happen before anything gets visible (= gets initialized) @@ -27,50 +41,130 @@ Controller::Controller() { format.setDepthBufferSize(16); QSurfaceFormat::setDefaultFormat(format); + + // configure the to-be-used sensor factory //SensorFactory::set(new SensorFactoryDummy()); //SensorFactory::set(new SensorFactoryOffline("/apps/android/workspace/YASMIN_DATA/offline/gyroacctestingfrank/nexus6/kleinerKreis_216steps_6runden_telefongerade.csv")); //SensorFactory::set(new SensorFactoryOffline("/apps/android/workspace/YASMIN_DATA/offline/gyroacctestingfrank/s3mini/kleinerKreis_225steps_6runden_telefongerade.csv")); //SensorFactory::set(new SensorFactoryOffline("/apps/android/workspace/YASMIN_DATA/offline/gyroacctestingfrank/s4/kleinerKreis_220steps_6runden_telefongeneigt.csv")); - SensorFactory::set(new SensorFactoryOffline("/apps/android/workspace/YASMIN_DATA/offline/bergwerk/path4/nexus/vor/1454776525797.csv")); - - + + //SensorFactory::set(new SensorFactoryOffline(Settings::Data::getOfflineDir() + "bergwerk/path3/nexus/vor/1454782562231.csv")); + //SensorFactory::set(new SensorFactoryOffline(Settings::Data::getOfflineDir() + "/bergwerk/path4/nexus/rueck/1454776724285_rueck.csv")); + SensorFactory::set(new SensorFactoryOffline(Settings::Data::getOfflineDir() + "/bergwerk/path4/nexus/vor/1454776525797.csv")); + +// SensorFactory::set(new SensorFactoryAndroid()); +// SensorFactory::get().getAccelerometer().start(); +// SensorFactory::get().getGyroscope().start(); +// SensorFactory::get().getBarometer().start(); +// SensorFactory::get().getWiFi().start(); + // create the main window mainWindow = new MainWindow(); + // attach logger + LoggerComposite* log = new LoggerComposite(); + log->addLogger(new LoggerCOUT()); + log->addLogger(new LoggerAndroid()); + log->addLogger(new LoggerUI(mainWindow->getInfoWidget())); + Log::setLogger(log); + + Assert::isTrue(connect(mainWindow->getMainMenu(), &MainMenu::onLoadButton, this, &Controller::onLoadButton), "connect() failed"); Assert::isTrue(connect(mainWindow->getMainMenu(), &MainMenu::onDebugButton, this, &Controller::onDebugButton), "connect() failed"); Assert::isTrue(connect(mainWindow->getMainMenu(), &MainMenu::onStartButton, this, &Controller::onStartButton), "connect() failed"); Assert::isTrue(connect(mainWindow->getMainMenu(), &MainMenu::onTransparentButton, this, &Controller::onTransparentButton), "connect() failed"); Assert::isTrue(connect(mainWindow->getMainMenu(), &MainMenu::onCameraButton, this, &Controller::onCameraButton), "connect() failed"); + Assert::isTrue(connect(mainWindow->getMainMenu(), &MainMenu::on3DButton, this, &Controller::on3DButton), "connect() failed"); // order is important! otherwise OpenGL fails! mainWindow->show(); +// // start all sensors +// SensorFactory::get().getAccelerometer().start(); +// SensorFactory::get().getGyroscope().start(); +// SensorFactory::get().getBarometer().start(); +// SensorFactory::get().getWiFi().start(); - // start all sensors - SensorFactory::get().getAccelerometer().start(); - SensorFactory::get().getGyroscope().start(); - SensorFactory::get().getBarometer().start(); - SensorFactory::get().getWiFi().start(); - } -MapView* Controller::getMapView() const { - return mainWindow->getMapView(); +MapView3D* Controller::getMapView3D() const { + return mainWindow->getMapView3D(); +} + +MapView2D* Controller::getMapView2D() const { + return mainWindow->getMapView2D(); } -void buildGridOnce(Grid* grid, Floorplan::IndoorMap* map, const std::string& saveFile) { +MainMenu* Controller::getMainMenu() const { + return mainWindow->getMainMenu(); +} + +InfoWidget* Controller::getInfoWidget() const { + return mainWindow->getInfoWidget(); +} + +#include +#include + +void buildGridOnce(Grid* grid, Floorplan::IndoorMap* map, const std::string& fpFile, const std::string& saveFile) { + //FloorplanHelper::align(map, grid->getGridSize_cm()); + + // ask questions + const QMessageBox::StandardButton replyWiFiFP = QMessageBox::question(nullptr, "WiFi", "Use Fingerprints for WiFiCalibration?\n\nYes: Use fingerprints and num-optimize AP-Params\nNo: Use APs from the map.xml (pos+params)", QMessageBox::Yes|QMessageBox::No); + + // WiFi setup + WiFiModelLogDistCeiling wifiModel(map); + if (replyWiFiFP == QMessageBox::Yes) { + VAPGrouper vg(VAPGrouper::Mode::LAST_MAC_DIGIT_TO_ZERO, VAPGrouper::Aggregation::AVERAGE); + WiFiCalibrationDataModel mdl(fpFile); + Assert::isFalse(mdl.getFingerprints().empty(), "no fingerprints available!"); + WiFiOptimizer opt(map, vg); + for (const WiFiFingerprint& fp : mdl.getFingerprints()) { + opt.addFingerprint(fp); + } + const std::vector res = opt.optimizeAll(); + WiFiGridEstimator::estimate(*grid, wifiModel, Settings::smartphoneAboveGround); + for (const WiFiOptimizer::APParamsMAC& ap : res) { + const WiFiModelLogDistCeiling::APEntry entry(ap.params.getPos(), ap.params.txp, ap.params.exp, ap.params.waf); + wifiModel.addAP(ap.mac, entry); + } + } else { + + // load all APs from the floorplan and use same TXP/EXP/WAF for all of them + wifiModel.loadAPs(map, Settings::WiFiModel::TXP, Settings::WiFiModel::EXP, Settings::WiFiModel::WAF); + + } + + // build the grid GridFactory gf(*grid); gf.build(map); + + // add node-importance Importance::addImportance(*grid); + + // stamp WiFi signal-strengths onto the grid + WiFiGridEstimator::estimate(*grid, wifiModel, Settings::smartphoneAboveGround); + + // serialize the grid std::ofstream out(saveFile, std::ofstream::binary); grid->write(out); out.close(); + +} + +void Controller::on3DButton() { + + static bool use3D = false; + use3D = !use3D; + + getMapView2D()->setVisible(!use3D); + getMapView3D()->setVisible( use3D); + } void Controller::onLoadButton() { @@ -83,6 +177,7 @@ void Controller::onLoadButton() { QFile fMap(dir.path() + "/map.xml"); QFile fGrid(dir.path() + "/grid.dat"); + QFile fWiFiFP(dir.path() + "/wifi_fp.dat"); Assert::isTrue(fMap.exists(), "map.xml missing"); //Assert::isTrue(fGrid.exists(), "grid.dat missing"); @@ -97,13 +192,15 @@ void Controller::onLoadButton() { std::ifstream inp(sGrid, std::ifstream::binary); //Assert::isTrue(inp.good(), "failed to open grid.dat"); + const std::string sWiFiFP = fWiFiFP.fileName().toStdString(); + // create a new, empty grid if (grid) {delete grid; grid = nullptr;} - grid = new Grid(20); + grid = new Grid(Settings::Grid::gridSize_cm); // grid.dat empty? -> build one and save it if (!inp.good() || (inp.peek()&&0) || inp.eof()) { - buildGridOnce(grid, im, sGrid); + buildGridOnce(grid, im, sWiFiFP, sGrid); } else { grid->read(inp); } @@ -112,8 +209,18 @@ void Controller::onLoadButton() { if (nav) {delete nav; nav = nullptr;} nav = new NavController(this, grid, im); - getMapView()->setMap(im); - getMapView()->showGridImportance(grid); + WiFiCalibrationDataModel* wifiCalib = new WiFiCalibrationDataModel(sWiFiFP); + + getMapView3D()->setMap(im); + getMapView2D()->setMap(wifiCalib, im); + + getMapView3D()->showGridImportance(grid); + getMapView2D()->showGridImportance(grid); + + getMapView3D()->setVisible(false); + + // attach ipin step logger + nav->addListener(&sl); } @@ -127,7 +234,7 @@ void Controller::onStartButton() { } void Controller::onTransparentButton() { - mainWindow->getMapView()->toggleRenderMode(); + mainWindow->getMapView3D()->toggleRenderMode(); } void Controller::onCameraButton() { diff --git a/Controller.h b/Controller.h index cbd3a77..a5c9989 100644 --- a/Controller.h +++ b/Controller.h @@ -1,6 +1,11 @@ #ifndef CONTROLLER_H #define CONTROLLER_H +#include "misc/fixc11.h" +#include "ipin/Scaler.h" +#include "ipin/StepLoggerWrapper.h" +#include "ipin/StepLoggerWrapperAndroid.h" + class MainWindow; class MainMenu; class MapView; @@ -10,6 +15,9 @@ class NavController; #include template class Grid; class MyGridNode; +class InfoWidget; +class MapView3D; +class MapView2D; namespace Floorplan { class IndoorMap; @@ -26,7 +34,19 @@ public: public: - MapView* getMapView() const; + MapView3D* getMapView3D() const; + MapView2D* getMapView2D() const; + + MainMenu* getMainMenu() const; + InfoWidget* getInfoWidget() const; + +protected: + + // scaling for the UAH building + IPINScaler scaler = IPINScaler(1869, 1869, 40.51312440, -3.34959080, -40.73112000, 0.07596002); + //StepLoggerWrapper sl; + StepLoggerWrapperAndroid sl; + private slots: @@ -36,6 +56,7 @@ private slots: void onTransparentButton(); void onCameraButton(); + void on3DButton(); private: diff --git a/Settings.h b/Settings.h index b116807..2832ba7 100644 --- a/Settings.h +++ b/Settings.h @@ -2,27 +2,88 @@ #define SETTINGS_H #include +#include + +#include namespace Settings { - const int numParticles = 3000; + const int numParticles = 2000; - const float turnSigma = 3.5; - - const float stepLength = 0.80; - const float stepSigma = 0.1; + namespace IMU { + const float turnSigma = 1.5; // 3.5 + const float stepLength = 0.80; + const float stepSigma = 0.10; + } const float smartphoneAboveGround = 1.3; - const float offlineSensorSpeedup = 2.5; + const float offlineSensorSpeedup = 2; + + namespace Grid { + constexpr int gridSize_cm = 20; + } - const GridPoint destination = GridPoint(70*100, 35*100, 0*100); + //const GridPoint destination = GridPoint(70*100, 35*100, 0*100); // use destination + const GridPoint destination = GridPoint(0,0,0); // do not use destination - const float wifiSigma = 9.0; - const float wifiTXP = -48; - const float wifiEXP = 2.5; - const float wifiWAF = -9.0; + namespace SensorDebug { + const Timestamp updateEvery = Timestamp::fromMS(200); + } + + namespace WiFiModel { + constexpr float sigma = 11.0; + /** if the wifi-signal-strengths are stored on the grid-nodes, this needs a grid rebuild! */ + constexpr float TXP = -48; + constexpr float EXP = 2.5; + constexpr float WAF = -5.0; + } + + + + namespace MapView { + constexpr int fps = 15; + const Timestamp msPerFrame = Timestamp::fromMS(1000/fps); + } + + namespace Filter { + const Timestamp updateEvery = Timestamp::fromMS(500); + constexpr bool useMainThread = false; // perform filtering in the main thread + } + + namespace Data { + + // notes + // copy: scp -P 2222 /tmp/grid.dat kazu@192.168.24.11:/storage/sdcard1/YASMIN/maps/car/ + // all: scp -P 2222 -r /apps/android/workspace/YASMIN_DATA/* kazu@192.168.24.11:/storage/sdcard1/YASMIN/ + + static inline std::string getRoot() { + #ifdef ANDROID + // const std::string folder = getenv("EXTERNAL_STORAGE") + std::string("/YASMIN/maps/"); // this is NOT the sdcard?! + // qDebug(folder.c_str()); + // return folder; + //return "/storage/sdcard1/YASMIN/"; + std::string f1 = "/storage/sdcard1/YASMIN/"; + std::string f2 = "/sdcard/YASMIN/"; + if (QFile(f1.c_str()).exists()) {return f1;} + if (QFile(f2.c_str()).exists()) {return f2;} + throw Exception("data folder missing"); + #else + return "/apps/android/workspace/YASMIN_DATA/"; + #endif + } + + /** get the directory where maps are stored */ + static inline std::string getMapDir() { + return getRoot() + "maps/"; + } + + static inline std::string getOfflineDir() { + return getRoot() + "offline/"; + } + + } } diff --git a/Stairs.h b/Stairs.h deleted file mode 100644 index 6a5d251..0000000 --- a/Stairs.h +++ /dev/null @@ -1,4 +0,0 @@ -#ifndef STAIRS_H -#define STAIRS_H - -#endif // STAIRS_H diff --git a/_android/src/MyActivity.java b/_android/src/MyActivity.java index 1f27874..62c4dda 100644 --- a/_android/src/MyActivity.java +++ b/_android/src/MyActivity.java @@ -7,10 +7,18 @@ public class MyActivity extends QtActivity { public static MyActivity act; + // IPIN2016 + private StepLoggerClient stepLogger; + + @Override public void onCreate(Bundle savedState) { MyActivity.act = this; super.onCreate(savedState); + + // IPIN2016 + stepLogger = new StepLoggerClient(this); + } @Override diff --git a/_android/src/StepLoggerClient.java b/_android/src/StepLoggerClient.java new file mode 100644 index 0000000..9bca174 --- /dev/null +++ b/_android/src/StepLoggerClient.java @@ -0,0 +1,79 @@ +package indoor.java; + +import android.app.IntentService; +import android.content.ComponentName; +import android.content.Intent; +import android.content.Context; +import android.content.ServiceConnection; +import android.os.IBinder; +import android.util.Log; + +import java.util.Timer; +import java.util.TimerTask; + +import it.cnr.isti.steplogger.IStepLoggerService; + + +/** + * An {@link IntentService} subclass for handling asynchronous task requests in + * a service on a separate handler thread. + */ +public class StepLoggerClient { + + private static StepLoggerClient instance; + + // Intent Service fields + private static String LOG_TAG = "StepLoggerClient"; + private boolean mustRun = true; + + // Bound Service fields + final String BOUNDSERVICE_PACKAGE = "it.cnr.isti.steplogger"; + final String BOUNDSERVICE_CLASS = ".StepLoggerService"; + IStepLoggerService mService; + + Boolean isBound = false; + Intent intentService = new Intent(); + + //Bound Service Connection + private ServiceConnection mConnection = new ServiceConnection() { + + public void onServiceConnected(ComponentName name, IBinder boundService) { + mService = IStepLoggerService.Stub.asInterface((IBinder) boundService); + Log.d(LOG_TAG, "onServiceConnected() : OK "); + isBound = true; + } + + public void onServiceDisconnected(ComponentName name) { + mService = null; + Log.d(LOG_TAG, "onServiceDisconnected() : OK "); + isBound = false; + } + + }; + + /** ctor */ + public StepLoggerClient(MyActivity act) { + + instance = this; + + intentService.setClassName(BOUNDSERVICE_PACKAGE, BOUNDSERVICE_PACKAGE + BOUNDSERVICE_CLASS); + act.bindService(intentService, mConnection , Context.BIND_AUTO_CREATE ); + + } + + /** static access from C++ */ + public static int log(double x, double y, double z) { + Log.d("me", "got values"); + instance._log(x,y,z); + return 1337; // return a magic-code that is checked within c++ + } + + private void _log(double x, double y, double z) { + Log.d("me", mService + ""); + if (mService == null) {return;} + try { + mService.logPosition(System.currentTimeMillis(), x, y, z); + } catch (final Exception e) {;} + } + +} diff --git a/_android/src/WiFi.java b/_android/src/WiFi.java index 2acecaf..450d7f3 100644 --- a/_android/src/WiFi.java +++ b/_android/src/WiFi.java @@ -34,13 +34,13 @@ public class WiFi { MyActivity act = MyActivity.act; manager = (WifiManager) act.getSystemService(Context.WIFI_SERVICE); - reset(); + // reset(); WiFi.receiver = new BroadcastReceiver() { public final void onReceive(final Context context, final Intent intent) { final byte[] result = serialize(manager.getScanResults()); + triggerOneScan(); WiFi.onScanComplete(result); - triggerOneScan(); } }; diff --git a/_android/src/aidl/it/cnr/isti/steplogger/IStepLoggerService.aidl b/_android/src/aidl/it/cnr/isti/steplogger/IStepLoggerService.aidl new file mode 100644 index 0000000..e783f7c --- /dev/null +++ b/_android/src/aidl/it/cnr/isti/steplogger/IStepLoggerService.aidl @@ -0,0 +1,8 @@ +// IMisuratoreService.aidl +package it.cnr.isti.steplogger; + +// Declare any non-default types here with import statements + +interface IStepLoggerService { + void logPosition(in long timestamp, in double x, in double y, in double z); +} diff --git a/ipin/Config.h b/ipin/Config.h new file mode 100644 index 0000000..dae9d7e --- /dev/null +++ b/ipin/Config.h @@ -0,0 +1,104 @@ +#ifndef EVALCONFIG_H +#define EVALCONFIG_H + +#include +#include +#include +#include +#include "IPINHelper.h" + +class EvalConfig { + +private: + + std::unordered_map keyVal; + +public: + + EvalConfig() { + ; + } + + /** get the value for the given key */ + const std::string& get(const std::string& key) { + static std::string empty = ""; + auto it = keyVal.find(key); + return (it == keyVal.end()) ? (empty) : (it->second); + } + +public: + + /** load the given configuration file */ + void load(const std::string& file) { + + std::ifstream inp(file); + + if (!inp.good()) {throw "error while opening config file " + file;} + + + std::string line; + std::string tmp; + while (!inp.eof()) { + + // read the next line (might be empty) + std::getline(inp, tmp); + if (tmp.empty()) {continue;} + + // in case of \r\n linebreaks, remove the remaining \r (might hereafter be empty) + if (tmp.back() == '\r') {tmp.erase(tmp.end()-1);} + if (tmp.empty()) {continue;} + + // multiline? + bool multiline = false; + if (tmp.back() == '\\') {multiline = true; tmp.erase(tmp.end()-1);} + + // attach + line += tmp; + + // complete line? -> parse it + if (!multiline) {parse(line); line = "";} + + } + + // trailing data + parse(line); + + inp.close(); + + } + +private: + + /** parse one line */ + void parse(const std::string& line) { + + // check + if (line.empty()) {return;} + if (line.front() == '[') {return;} + + // split key and value + const size_t pos = line.find(" = "); + if (pos == std::string::npos) {throw "something wrong";} + + const std::string key = line.substr(0, pos); + const std::string val = line.substr(pos+3); + + // add + keyVal[key] = val; + + } + + /** get the eval config.ini filename */ + std::string getConfigFile() const { + + const std::string folder = IPINHelper::getDataFolder(); + const std::string file = folder + "it.cnr.isti.steplogger.config.ini"; + return file; + + } + + + +}; + +#endif // EVALCONFIG_H diff --git a/ipin/IPINHelper.h b/ipin/IPINHelper.h new file mode 100644 index 0000000..973f721 --- /dev/null +++ b/ipin/IPINHelper.h @@ -0,0 +1,22 @@ +#ifndef IPINHELPER_H +#define IPINHELPER_H + +#include + +class IPINHelper { + +public: + + /** get the StepLogger data folder */ + static std::string getDataFolder() { + +#ifdef ANDROID + return getenv("DIRECTORY_DOWNLOADS"); +#else + return "/apps/android/workspace/YASMIN_DATA/"; +#endif + + } +}; + +#endif // IPINHELPER_H diff --git a/ipin/Scaler.h b/ipin/Scaler.h new file mode 100644 index 0000000..f48d08f --- /dev/null +++ b/ipin/Scaler.h @@ -0,0 +1,104 @@ +#ifndef IPIN_SCALER_H +#define IPIN_SCALER_H + +#include +#include + +struct IPIN { + double lat; + double lon; + double floorNr; + IPIN(const double lat, const double lon, const double floorNr) : lat(lat), lon(lon), floorNr(floorNr) {;} +}; + +class IPINScaler { + +private: + + int w; + int h; + double cenLat; + double cenLon; + double rotDeg; + double mPerPx; + + Point2 mapCenter_m; + + double refLat; + double m_per_deg_lat; + double m_per_deg_lon; + + const float fixedFloorHeight = 4.0f; + +public: + + + /** image width, image height, map-center (lat/lon), map-rotation, meter<->pixel conversion factor */ + IPINScaler(int w, int h, double cenLat, double cenLon, double rotDeg, double mPerPx) : w(w), h(h), cenLat(cenLat), cenLon(cenLon), rotDeg(rotDeg), mPerPx(mPerPx) { + + mapCenter_m = Point2( (w*mPerPx/2), (h*mPerPx/2) ); + + refLat = cenLat / 180.0 * M_PI; + m_per_deg_lat = 111132.954 - 559.822 * std::cos( 2.0 * refLat ) + 1.175 * std::cos( 4.0 * refLat); + m_per_deg_lon = 111132.954 * std::cos ( refLat ); + + } + + + + + /** convert from (x,y,z) to (lat,lon,floorNr) */ + IPIN toIPIN3(const float x, const float y, const float z) const { + + Point2 pos(x,y); + + // move to (0,0) + pos -= mapCenter_m; + + // undo the rotation + pos = pos.rotated(-rotDeg / 180 * M_PI); + + const double lat = cenLat + (pos.y / m_per_deg_lat); + const double lon = cenLon + (pos.x / m_per_deg_lon); + const double floorNr = z / fixedFloorHeight; + + return IPIN(lat, lon, floorNr); + + } + + IPIN toIPIN3(const Point3 p) const { + return toIPIN3(p.x, p.y, p.z); + } + + Point3 convert3D(const IPIN& ipin) const { + return convert3D(ipin.lat, ipin.lon, ipin.floorNr); + } + + Point3 convert3D(double lat, double lon, float floorNr) const { + + Point2 p2 = convert2D(lat, lon); + + return Point3(p2.x, p2.y, floorNr * fixedFloorHeight); + + } + + Point2 convert2D(double lat, double lon) const { + + const double y_m = +(lat-cenLat) * m_per_deg_lat; + const double x_m = +(lon-cenLon) * m_per_deg_lon; + + // rotate (our map is axis aligned) + Point2 pos(x_m, y_m); + pos = pos.rotated(rotDeg / 180 * M_PI); + + // apply movement + pos += mapCenter_m; + + return pos; + + } + + +}; + +#endif // IPIN_SCALER_H diff --git a/ipin/StepLogger.h b/ipin/StepLogger.h new file mode 100644 index 0000000..2b978b6 --- /dev/null +++ b/ipin/StepLogger.h @@ -0,0 +1,188 @@ +#ifndef STEPLOGGER_H +#define STEPLOGGER_H + +#include +#include +#include +#include +#include + +#include +#include "Scaler.h" +#include "Config.h" +#include "IPINHelper.h" + +class StepLogger { + +private: + + EvalConfig cfg; + std::string configFile; + std::string competitorID = "navindoor"; + + + std::ofstream outButtons; + std::ofstream outPositions; + + /** all step-logger wayponts defined within the config file */ + std::vector waypoints; + int curWP = 0; + + +public: + + /** ctor with the map<->world scaler */ + StepLogger() { + loadConfig(); + start(); + } + +public: + + /** log current timestamp + waypoint and proceed with the next one */ + void onButtonPress() { + + // sanity check + if (isDone()) {throw "all waypoints were processed";} + + // construct output string + std::stringstream ss; + std::string wpEntry = waypoints[curWP]; ++curWP; + wpEntry = replace(wpEntry, ":" , " : "); + ss << Timestamp::fromUnixTime().ms() << " : " << wpEntry << "\r\n"; + + // log + std::cout << ss.str() << std::flush; + outButtons << ss.str(); outButtons.flush(); + + + } + + /** all waypoints done? */ + bool isDone() const { + return curWP >= (int)waypoints.size(); + } + + + /** log our map-relative format */ + void onNewEstimation(const double lat, const double lon, const double floorNr) { + + // construct output string + std::stringstream ss; + ss << Timestamp::fromUnixTime().ms() << " : " << lat << " : " << lon << " : " << floorNr << "\r\n"; + + // log + std::cout << ss.str() << std::endl; + outPositions << ss.str(); outPositions.flush(); + + } + + /** get the current waypoint's number, starting at 0 */ + int getCurrentWaypointNumber() const { + return curWP; + } + +private: + + /** split the given string */ + std::vector split(const std::string& str, const char delim) { + std::vector res; + int start = 0; + while (true) { + size_t pos = str.find(delim, start); + if (pos == std::string::npos) {break;} + const std::string sub = str.substr(start, pos-start); + res.push_back(sub); + start = pos + 1; + } + return res; + } + + /** string replacement helper */ + std::string replace(std::string str, const std::string& from, const std::string& to) { + size_t start_pos = 0; + while((start_pos = str.find(from, start_pos)) != std::string::npos) { + str.replace(start_pos, from.length(), to); + start_pos += to.length(); + } + return str; + } + + /** get the current time as [YYYYMMDD]T[HHMMSS] */ + std::string getDate() const { + const char* format = "%Y%m%dT%H%m%S"; + std::time_t t = std::time(nullptr); + struct tm* tt = std::localtime(&t); + + char buf[128]; + strftime(buf, 128, format, tt); + return std::string(buf); + +// std::stringstream ss; +// ss << std::put_time(tt, format); +// return ss.str(); + } + + +private: + + /** load the config.ini and parse the waypoints */ + void loadConfig() { + cfg.load(IPINHelper::getDataFolder() + "it.cnr.isti.steplogger.config.ini"); + const std::string tmp = cfg.get("counter"); + waypoints = split(tmp, ','); + } + + /** create the data-folder, open the two output files and perform sanity checks */ + void start() { + + // get the output data folder and construct filenames + const std::string folder = getOutputFolder(); + const std::string fBtn = folder + "buttonsPressed.log"; + const std::string fPos = folder + "positions.log"; + + // open two output files + outButtons.open(fBtn); if (!outButtons.good()) {throw "error while creating file";} + outPositions.open(fPos); if (!outPositions.good()) {throw "error while creating file";} + + // reset current WayPoint + curWP = 0; + + } + + + /** get a DateTime dependent data folder */ + std::string getOutputFolder() { + const std::string& folder = IPINHelper::getDataFolder(); + const std::string date = getDate(); + const std::string sub = folder + date + "_" + competitorID + "/"; + mkdir(sub.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); + return sub; + } + + + + + + // // config file + // Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + + // File.separator + + // "it.cnr.isti.steplogger.config.ini"; + + // buttonsPressed.log + // milliseconds " : " number-starting-at-1" : "???" : "???" : "floor? // see configFile config.ini + // java current time millis + // positions.log + // timestamp " " x " " y " " z + + // storage/sdcard0/Download/it.cnr.isti.steplogger/ + + // Within the folder it.cnr.isti.steplogger/ StepLogger creates a folder for every measurement session, the logs are placed in folder whose name follows this convention: + + // [YearMonthDay]T[HourMinutesSeconds][Competitor ID] + // // Coordinates will need to be in the WGS84 coordinate system (longitude and latitude) for x, y, + // //and the number of floor (an integer starting from 0) for z. + +}; + +#endif // STEPLOGGER_H diff --git a/ipin/StepLoggerWrapper.h b/ipin/StepLoggerWrapper.h new file mode 100644 index 0000000..9da6a59 --- /dev/null +++ b/ipin/StepLoggerWrapper.h @@ -0,0 +1,97 @@ +#ifndef STEPLOGGERWRAPPER_H +#define STEPLOGGERWRAPPER_H + +#include "Scaler.h" +#include "StepLogger.h" +#include "../nav/NavControllerListener.h" + +#include +#include +#include +#include +#include + +/** + * helper class to connect our NavigationController with the StepLogger + */ +class StepLoggerWrapper : public StepLogger, public NavControllerListener { + +private: + + /** convert from our position-format to ipin position-format */ + IPINScaler& scaler; + + QMainWindow* window; + QPushButton* btn; + +public: + + /** ctor */ + StepLoggerWrapper(IPINScaler& scaler) : scaler(scaler) { + setupUI(); + } + + /** + * event fired every 500ms from the navigation controller. + * convert from our format to IPIN format + * and pass it to the logger + */ + void onNewEstimation(const Point3 pos_m) override { + + // convert from our coordinate system (meter relative to (0,0,0)) to the WGS84 format + const IPIN ipin = scaler.toIPIN3(pos_m); + + // inform the logger + StepLogger::onNewEstimation(ipin.lat, ipin.lon, ipin.floorNr); + + } + +private: + + /** create a clickable check button */ + void setupUI() { + + window = new QMainWindow(); + //window->setTitle("StepLogger"); + btn = new QPushButton(window); + + // almost fullscreen + QRect geom = QDesktopWidget().availableGeometry(); + const int w = geom.width() * 0.9; + const int h = geom.height() * 0.6; + + // center and set always-on-top + window->setGeometry(geom.width()/2 - w/2, geom.height()/2 - h/2, w, h); + const Qt::WindowFlags flags = window->windowFlags(); + window->setWindowFlags(flags | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint); + + + btn->setGeometry(5,5,w-5-5,h-5-5); + window->show(); + + // button clicked -> next waypoint + btn->connect(btn, &QPushButton::clicked, [&] () { + StepLogger::onButtonPress(); + updateButton(); + }); + + // show the current waypoint + updateButton(); + + } + + /** update the current button label */ + void updateButton() { + + // show the number of the next waypoint + const int nr = getCurrentWaypointNumber() + 1; + btn->setText(QString::number(nr)); + + // button is visible when we are not yet done + btn->setVisible(!StepLogger::isDone()); + + } + +}; + +#endif // STEPLOGGERWRAPPER_H diff --git a/ipin/StepLoggerWrapperAndroid.h b/ipin/StepLoggerWrapperAndroid.h new file mode 100644 index 0000000..114e08a --- /dev/null +++ b/ipin/StepLoggerWrapperAndroid.h @@ -0,0 +1,61 @@ +#ifndef STEPLOGGERWRAPPERANDROID_H +#define STEPLOGGERWRAPPERANDROID_H + +#include "Scaler.h" +#include "../nav/NavControllerListener.h" +#include + +#ifdef Android +#include +#endif + +/** + * sends the position-estimation-result to the step-logger service + */ +class StepLoggerWrapperAndroid : public NavControllerListener { + +public: + + /** convert from our position-format to ipin position-format */ + IPINScaler& scaler; + + +public: + + /** ctor */ + StepLoggerWrapperAndroid(IPINScaler& scaler) : scaler(scaler) { + ; + } + + + /** + * event fired every 500ms from the navigation controller. + * convert from our format to IPIN format + * and pass it to the logger + */ + void onNewEstimation(const Point3 pos_m) override { + + // convert from our coordinate system (meter relative to (0,0,0)) to the WGS84 format + const IPIN ipin = scaler.toIPIN3(pos_m); + + // inform the logger + log(ipin.lon, ipin.lat, ipin.floorNr); + + } + +private: + + /** call java */ + void log(const double x, const double y, const double z) { + +#ifdef Android + Log::add("SLWA", "calling android with lon/lat/floor"); + int res = QAndroidJniObject::callStaticMethod("indoor/java/StepLoggerClient", "log", "(DDD)I", x, y, z); + if (res != 1337) {throw Exception("error while logging");} +#endif + + } + +}; + +#endif // STEPLOGGERWRAPPERANDROID_H diff --git a/lib/tinyxml/tinyxml2.cpp b/lib/tinyxml/tinyxml2.cpp new file mode 100644 index 0000000..df49d0d --- /dev/null +++ b/lib/tinyxml/tinyxml2.cpp @@ -0,0 +1,2467 @@ +/* +Original code by Lee Thomason (www.grinninglizard.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#include "tinyxml2.h" + +#include // yes, this one new style header, is in the Android SDK. +#if defined(ANDROID_NDK) || defined(__QNXNTO__) +# include +# include +#else +# include +# include +#endif + +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) + // Microsoft Visual Studio, version 2005 and higher. Not WinCE. + /*int _snprintf_s( + char *buffer, + size_t sizeOfBuffer, + size_t count, + const char *format [, + argument] ... + );*/ + static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) + { + va_list va; + va_start( va, format ); + int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); + va_end( va ); + return result; + } + + static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va ) + { + int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); + return result; + } + + #define TIXML_VSCPRINTF _vscprintf + #define TIXML_SSCANF sscanf_s +#elif defined _MSC_VER + // Microsoft Visual Studio 2003 and earlier or WinCE + #define TIXML_SNPRINTF _snprintf + #define TIXML_VSNPRINTF _vsnprintf + #define TIXML_SSCANF sscanf + #if (_MSC_VER < 1400 ) && (!defined WINCE) + // Microsoft Visual Studio 2003 and not WinCE. + #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. + #else + // Microsoft Visual Studio 2003 and earlier or WinCE. + static inline int TIXML_VSCPRINTF( const char* format, va_list va ) + { + int len = 512; + for (;;) { + len = len*2; + char* str = new char[len](); + const int required = _vsnprintf(str, len, format, va); + delete[] str; + if ( required != -1 ) { + TIXMLASSERT( required >= 0 ); + len = required; + break; + } + } + TIXMLASSERT( len >= 0 ); + return len; + } + #endif +#else + // GCC version 3 and higher + //#warning( "Using sn* functions." ) + #define TIXML_SNPRINTF snprintf + #define TIXML_VSNPRINTF vsnprintf + static inline int TIXML_VSCPRINTF( const char* format, va_list va ) + { + int len = vsnprintf( 0, 0, format, va ); + TIXMLASSERT( len >= 0 ); + return len; + } + #define TIXML_SSCANF sscanf +#endif + + +static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF +static const char LF = LINE_FEED; +static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out +static const char CR = CARRIAGE_RETURN; +static const char SINGLE_QUOTE = '\''; +static const char DOUBLE_QUOTE = '\"'; + +// Bunch of unicode info at: +// http://www.unicode.org/faq/utf_bom.html +// ef bb bf (Microsoft "lead bytes") - designates UTF-8 + +static const unsigned char TIXML_UTF_LEAD_0 = 0xefU; +static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; +static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; + +namespace tinyxml2 +{ + +struct Entity { + const char* pattern; + int length; + char value; +}; + +static const int NUM_ENTITIES = 5; +static const Entity entities[NUM_ENTITIES] = { + { "quot", 4, DOUBLE_QUOTE }, + { "amp", 3, '&' }, + { "apos", 4, SINGLE_QUOTE }, + { "lt", 2, '<' }, + { "gt", 2, '>' } +}; + + +StrPair::~StrPair() +{ + Reset(); +} + + +void StrPair::TransferTo( StrPair* other ) +{ + if ( this == other ) { + return; + } + // This in effect implements the assignment operator by "moving" + // ownership (as in auto_ptr). + + TIXMLASSERT( other->_flags == 0 ); + TIXMLASSERT( other->_start == 0 ); + TIXMLASSERT( other->_end == 0 ); + + other->Reset(); + + other->_flags = _flags; + other->_start = _start; + other->_end = _end; + + _flags = 0; + _start = 0; + _end = 0; +} + +void StrPair::Reset() +{ + if ( _flags & NEEDS_DELETE ) { + delete [] _start; + } + _flags = 0; + _start = 0; + _end = 0; +} + + +void StrPair::SetStr( const char* str, int flags ) +{ + TIXMLASSERT( str ); + Reset(); + size_t len = strlen( str ); + TIXMLASSERT( _start == 0 ); + _start = new char[ len+1 ]; + memcpy( _start, str, len+1 ); + _end = _start + len; + _flags = flags | NEEDS_DELETE; +} + + +char* StrPair::ParseText( char* p, const char* endTag, int strFlags ) +{ + TIXMLASSERT( endTag && *endTag ); + + char* start = p; + char endChar = *endTag; + size_t length = strlen( endTag ); + + // Inner loop of text parsing. + while ( *p ) { + if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { + Set( start, p, strFlags ); + return p + length; + } + ++p; + } + return 0; +} + + +char* StrPair::ParseName( char* p ) +{ + if ( !p || !(*p) ) { + return 0; + } + if ( !XMLUtil::IsNameStartChar( *p ) ) { + return 0; + } + + char* const start = p; + ++p; + while ( *p && XMLUtil::IsNameChar( *p ) ) { + ++p; + } + + Set( start, p, 0 ); + return p; +} + + +void StrPair::CollapseWhitespace() +{ + // Adjusting _start would cause undefined behavior on delete[] + TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 ); + // Trim leading space. + _start = XMLUtil::SkipWhiteSpace( _start ); + + if ( *_start ) { + char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( *p ) { + if ( XMLUtil::IsWhiteSpace( *p )) { + p = XMLUtil::SkipWhiteSpace( p ); + if ( *p == 0 ) { + break; // don't write to q; this trims the trailing space. + } + *q = ' '; + ++q; + } + *q = *p; + ++q; + ++p; + } + *q = 0; + } +} + + +const char* StrPair::GetStr() +{ + TIXMLASSERT( _start ); + TIXMLASSERT( _end ); + if ( _flags & NEEDS_FLUSH ) { + *_end = 0; + _flags ^= NEEDS_FLUSH; + + if ( _flags ) { + char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( p < _end ) { + if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { + // CR-LF pair becomes LF + // CR alone becomes LF + // LF-CR becomes LF + if ( *(p+1) == LF ) { + p += 2; + } + else { + ++p; + } + *q++ = LF; + } + else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { + if ( *(p+1) == CR ) { + p += 2; + } + else { + ++p; + } + *q++ = LF; + } + else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { + // Entities handled by tinyXML2: + // - special entities in the entity table [in/out] + // - numeric character reference [in] + // 中 or 中 + + if ( *(p+1) == '#' ) { + const int buflen = 10; + char buf[buflen] = { 0 }; + int len = 0; + char* adjusted = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); + if ( adjusted == 0 ) { + *q = *p; + ++p; + ++q; + } + else { + TIXMLASSERT( 0 <= len && len <= buflen ); + TIXMLASSERT( q + len <= adjusted ); + p = adjusted; + memcpy( q, buf, len ); + q += len; + } + } + else { + bool entityFound = false; + for( int i = 0; i < NUM_ENTITIES; ++i ) { + const Entity& entity = entities[i]; + if ( strncmp( p + 1, entity.pattern, entity.length ) == 0 + && *( p + entity.length + 1 ) == ';' ) { + // Found an entity - convert. + *q = entity.value; + ++q; + p += entity.length + 2; + entityFound = true; + break; + } + } + if ( !entityFound ) { + // fixme: treat as error? + ++p; + ++q; + } + } + } + else { + *q = *p; + ++p; + ++q; + } + } + *q = 0; + } + // The loop below has plenty going on, and this + // is a less useful mode. Break it out. + if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) { + CollapseWhitespace(); + } + _flags = (_flags & NEEDS_DELETE); + } + TIXMLASSERT( _start ); + return _start; +} + + + + +// --------- XMLUtil ----------- // + +const char* XMLUtil::ReadBOM( const char* p, bool* bom ) +{ + TIXMLASSERT( p ); + TIXMLASSERT( bom ); + *bom = false; + const unsigned char* pu = reinterpret_cast(p); + // Check for BOM: + if ( *(pu+0) == TIXML_UTF_LEAD_0 + && *(pu+1) == TIXML_UTF_LEAD_1 + && *(pu+2) == TIXML_UTF_LEAD_2 ) { + *bom = true; + p += 3; + } + TIXMLASSERT( p ); + return p; +} + + +void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) +{ + const unsigned long BYTE_MASK = 0xBF; + const unsigned long BYTE_MARK = 0x80; + const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + + if (input < 0x80) { + *length = 1; + } + else if ( input < 0x800 ) { + *length = 2; + } + else if ( input < 0x10000 ) { + *length = 3; + } + else if ( input < 0x200000 ) { + *length = 4; + } + else { + *length = 0; // This code won't convert this correctly anyway. + return; + } + + output += *length; + + // Scary scary fall throughs. + switch (*length) { + case 4: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 3: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 2: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + case 1: + --output; + *output = (char)(input | FIRST_BYTE_MARK[*length]); + break; + default: + TIXMLASSERT( false ); + } +} + + +const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) +{ + // Presume an entity, and pull it out. + *length = 0; + + if ( *(p+1) == '#' && *(p+2) ) { + unsigned long ucs = 0; + TIXMLASSERT( sizeof( ucs ) >= 4 ); + ptrdiff_t delta = 0; + unsigned mult = 1; + static const char SEMICOLON = ';'; + + if ( *(p+2) == 'x' ) { + // Hexadecimal. + const char* q = p+3; + if ( !(*q) ) { + return 0; + } + + q = strchr( q, SEMICOLON ); + + if ( !q ) { + return 0; + } + TIXMLASSERT( *q == SEMICOLON ); + + delta = q-p; + --q; + + while ( *q != 'x' ) { + unsigned int digit = 0; + + if ( *q >= '0' && *q <= '9' ) { + digit = *q - '0'; + } + else if ( *q >= 'a' && *q <= 'f' ) { + digit = *q - 'a' + 10; + } + else if ( *q >= 'A' && *q <= 'F' ) { + digit = *q - 'A' + 10; + } + else { + return 0; + } + TIXMLASSERT( digit >= 0 && digit < 16); + TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); + ucs += digitScaled; + TIXMLASSERT( mult <= UINT_MAX / 16 ); + mult *= 16; + --q; + } + } + else { + // Decimal. + const char* q = p+2; + if ( !(*q) ) { + return 0; + } + + q = strchr( q, SEMICOLON ); + + if ( !q ) { + return 0; + } + TIXMLASSERT( *q == SEMICOLON ); + + delta = q-p; + --q; + + while ( *q != '#' ) { + if ( *q >= '0' && *q <= '9' ) { + const unsigned int digit = *q - '0'; + TIXMLASSERT( digit >= 0 && digit < 10); + TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); + ucs += digitScaled; + } + else { + return 0; + } + TIXMLASSERT( mult <= UINT_MAX / 10 ); + mult *= 10; + --q; + } + } + // convert the UCS to UTF-8 + ConvertUTF32ToUTF8( ucs, value, length ); + return p + delta + 1; + } + return p+1; +} + + +void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); +} + + +void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); +} + + +void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%d", v ? 1 : 0 ); +} + +/* + ToStr() of a number is a very tricky topic. + https://github.com/leethomason/tinyxml2/issues/106 +*/ +void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v ); +} + + +void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v ); +} + + +bool XMLUtil::ToInt( const char* str, int* value ) +{ + if ( TIXML_SSCANF( str, "%d", value ) == 1 ) { + return true; + } + return false; +} + +bool XMLUtil::ToUnsigned( const char* str, unsigned *value ) +{ + if ( TIXML_SSCANF( str, "%u", value ) == 1 ) { + return true; + } + return false; +} + +bool XMLUtil::ToBool( const char* str, bool* value ) +{ + int ival = 0; + if ( ToInt( str, &ival )) { + *value = (ival==0) ? false : true; + return true; + } + if ( StringEqual( str, "true" ) ) { + *value = true; + return true; + } + else if ( StringEqual( str, "false" ) ) { + *value = false; + return true; + } + return false; +} + + +bool XMLUtil::ToFloat( const char* str, float* value ) +{ + if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { + return true; + } + return false; +} + +bool XMLUtil::ToDouble( const char* str, double* value ) +{ + if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { + return true; + } + return false; +} + + +char* XMLDocument::Identify( char* p, XMLNode** node ) +{ + TIXMLASSERT( node ); + TIXMLASSERT( p ); + char* const start = p; + p = XMLUtil::SkipWhiteSpace( p ); + if( !*p ) { + *node = 0; + TIXMLASSERT( p ); + return p; + } + + // These strings define the matching patterns: + static const char* xmlHeader = { "_memPool = &_commentPool; + p += xmlHeaderLen; + } + else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) { + TIXMLASSERT( sizeof( XMLComment ) == _commentPool.ItemSize() ); + returnNode = new (_commentPool.Alloc()) XMLComment( this ); + returnNode->_memPool = &_commentPool; + p += commentHeaderLen; + } + else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) { + TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() ); + XMLText* text = new (_textPool.Alloc()) XMLText( this ); + returnNode = text; + returnNode->_memPool = &_textPool; + p += cdataHeaderLen; + text->SetCData( true ); + } + else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) { + TIXMLASSERT( sizeof( XMLUnknown ) == _commentPool.ItemSize() ); + returnNode = new (_commentPool.Alloc()) XMLUnknown( this ); + returnNode->_memPool = &_commentPool; + p += dtdHeaderLen; + } + else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) { + TIXMLASSERT( sizeof( XMLElement ) == _elementPool.ItemSize() ); + returnNode = new (_elementPool.Alloc()) XMLElement( this ); + returnNode->_memPool = &_elementPool; + p += elementHeaderLen; + } + else { + TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() ); + returnNode = new (_textPool.Alloc()) XMLText( this ); + returnNode->_memPool = &_textPool; + p = start; // Back it up, all the text counts. + } + + TIXMLASSERT( returnNode ); + TIXMLASSERT( p ); + *node = returnNode; + return p; +} + + +bool XMLDocument::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + if ( visitor->VisitEnter( *this ) ) { + for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) { + break; + } + } + } + return visitor->VisitExit( *this ); +} + + +// --------- XMLNode ----------- // + +XMLNode::XMLNode( XMLDocument* doc ) : + _document( doc ), + _parent( 0 ), + _firstChild( 0 ), _lastChild( 0 ), + _prev( 0 ), _next( 0 ), + _memPool( 0 ) +{ +} + + +XMLNode::~XMLNode() +{ + DeleteChildren(); + if ( _parent ) { + _parent->Unlink( this ); + } +} + +const char* XMLNode::Value() const +{ + // Catch an edge case: XMLDocuments don't have a a Value. Carefully return nullptr. + if ( this->ToDocument() ) + return 0; + return _value.GetStr(); +} + +void XMLNode::SetValue( const char* str, bool staticMem ) +{ + if ( staticMem ) { + _value.SetInternedStr( str ); + } + else { + _value.SetStr( str ); + } +} + + +void XMLNode::DeleteChildren() +{ + while( _firstChild ) { + TIXMLASSERT( _lastChild ); + TIXMLASSERT( _firstChild->_document == _document ); + XMLNode* node = _firstChild; + Unlink( node ); + + DeleteNode( node ); + } + _firstChild = _lastChild = 0; +} + + +void XMLNode::Unlink( XMLNode* child ) +{ + TIXMLASSERT( child ); + TIXMLASSERT( child->_document == _document ); + TIXMLASSERT( child->_parent == this ); + if ( child == _firstChild ) { + _firstChild = _firstChild->_next; + } + if ( child == _lastChild ) { + _lastChild = _lastChild->_prev; + } + + if ( child->_prev ) { + child->_prev->_next = child->_next; + } + if ( child->_next ) { + child->_next->_prev = child->_prev; + } + child->_parent = 0; +} + + +void XMLNode::DeleteChild( XMLNode* node ) +{ + TIXMLASSERT( node ); + TIXMLASSERT( node->_document == _document ); + TIXMLASSERT( node->_parent == this ); + Unlink( node ); + DeleteNode( node ); +} + + +XMLNode* XMLNode::InsertEndChild( XMLNode* addThis ) +{ + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + InsertChildPreamble( addThis ); + + if ( _lastChild ) { + TIXMLASSERT( _firstChild ); + TIXMLASSERT( _lastChild->_next == 0 ); + _lastChild->_next = addThis; + addThis->_prev = _lastChild; + _lastChild = addThis; + + addThis->_next = 0; + } + else { + TIXMLASSERT( _firstChild == 0 ); + _firstChild = _lastChild = addThis; + + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; +} + + +XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis ) +{ + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + InsertChildPreamble( addThis ); + + if ( _firstChild ) { + TIXMLASSERT( _lastChild ); + TIXMLASSERT( _firstChild->_prev == 0 ); + + _firstChild->_prev = addThis; + addThis->_next = _firstChild; + _firstChild = addThis; + + addThis->_prev = 0; + } + else { + TIXMLASSERT( _lastChild == 0 ); + _firstChild = _lastChild = addThis; + + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; +} + + +XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ) +{ + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + + TIXMLASSERT( afterThis ); + + if ( afterThis->_parent != this ) { + TIXMLASSERT( false ); + return 0; + } + + if ( afterThis->_next == 0 ) { + // The last node or the only node. + return InsertEndChild( addThis ); + } + InsertChildPreamble( addThis ); + addThis->_prev = afterThis; + addThis->_next = afterThis->_next; + afterThis->_next->_prev = addThis; + afterThis->_next = addThis; + addThis->_parent = this; + return addThis; +} + + + + +const XMLElement* XMLNode::FirstChildElement( const char* name ) const +{ + for( const XMLNode* node = _firstChild; node; node = node->_next ) { + const XMLElement* element = node->ToElement(); + if ( element ) { + if ( !name || XMLUtil::StringEqual( element->Name(), name ) ) { + return element; + } + } + } + return 0; +} + + +const XMLElement* XMLNode::LastChildElement( const char* name ) const +{ + for( const XMLNode* node = _lastChild; node; node = node->_prev ) { + const XMLElement* element = node->ToElement(); + if ( element ) { + if ( !name || XMLUtil::StringEqual( element->Name(), name ) ) { + return element; + } + } + } + return 0; +} + + +const XMLElement* XMLNode::NextSiblingElement( const char* name ) const +{ + for( const XMLNode* node = _next; node; node = node->_next ) { + const XMLElement* element = node->ToElement(); + if ( element + && (!name || XMLUtil::StringEqual( name, element->Name() ))) { + return element; + } + } + return 0; +} + + +const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const +{ + for( const XMLNode* node = _prev; node; node = node->_prev ) { + const XMLElement* element = node->ToElement(); + if ( element + && (!name || XMLUtil::StringEqual( name, element->Name() ))) { + return element; + } + } + return 0; +} + + +char* XMLNode::ParseDeep( char* p, StrPair* parentEnd ) +{ + // This is a recursive method, but thinking about it "at the current level" + // it is a pretty simple flat list: + // + // + // + // With a special case: + // + // + // + // + // Where the closing element (/foo) *must* be the next thing after the opening + // element, and the names must match. BUT the tricky bit is that the closing + // element will be read by the child. + // + // 'endTag' is the end tag for this node, it is returned by a call to a child. + // 'parentEnd' is the end tag for the parent, which is filled in and returned. + + while( p && *p ) { + XMLNode* node = 0; + + p = _document->Identify( p, &node ); + if ( node == 0 ) { + break; + } + + StrPair endTag; + p = node->ParseDeep( p, &endTag ); + if ( !p ) { + DeleteNode( node ); + if ( !_document->Error() ) { + _document->SetError( XML_ERROR_PARSING, 0, 0 ); + } + break; + } + + XMLDeclaration* decl = node->ToDeclaration(); + if ( decl ) { + // A declaration can only be the first child of a document. + // Set error, if document already has children. + if ( !_document->NoChildren() ) { + _document->SetError( XML_ERROR_PARSING_DECLARATION, decl->Value(), 0); + DeleteNode( decl ); + break; + } + } + + XMLElement* ele = node->ToElement(); + if ( ele ) { + // We read the end tag. Return it to the parent. + if ( ele->ClosingType() == XMLElement::CLOSING ) { + if ( parentEnd ) { + ele->_value.TransferTo( parentEnd ); + } + node->_memPool->SetTracked(); // created and then immediately deleted. + DeleteNode( node ); + return p; + } + + // Handle an end tag returned to this level. + // And handle a bunch of annoying errors. + bool mismatch = false; + if ( endTag.Empty() ) { + if ( ele->ClosingType() == XMLElement::OPEN ) { + mismatch = true; + } + } + else { + if ( ele->ClosingType() != XMLElement::OPEN ) { + mismatch = true; + } + else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) { + mismatch = true; + } + } + if ( mismatch ) { + _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, ele->Name(), 0 ); + DeleteNode( node ); + break; + } + } + InsertEndChild( node ); + } + return 0; +} + +void XMLNode::DeleteNode( XMLNode* node ) +{ + if ( node == 0 ) { + return; + } + MemPool* pool = node->_memPool; + node->~XMLNode(); + pool->Free( node ); +} + +void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const +{ + TIXMLASSERT( insertThis ); + TIXMLASSERT( insertThis->_document == _document ); + + if ( insertThis->_parent ) + insertThis->_parent->Unlink( insertThis ); + else + insertThis->_memPool->SetTracked(); +} + +// --------- XMLText ---------- // +char* XMLText::ParseDeep( char* p, StrPair* ) +{ + const char* start = p; + if ( this->CData() ) { + p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_CDATA, start, 0 ); + } + return p; + } + else { + int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; + if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { + flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; + } + + p = _value.ParseText( p, "<", flags ); + if ( p && *p ) { + return p-1; + } + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_TEXT, start, 0 ); + } + } + return 0; +} + + +XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? + text->SetCData( this->CData() ); + return text; +} + + +bool XMLText::ShallowEqual( const XMLNode* compare ) const +{ + const XMLText* text = compare->ToText(); + return ( text && XMLUtil::StringEqual( text->Value(), Value() ) ); +} + + +bool XMLText::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + + +// --------- XMLComment ---------- // + +XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLComment::~XMLComment() +{ +} + + +char* XMLComment::ParseDeep( char* p, StrPair* ) +{ + // Comment parses as text. + const char* start = p; + p = _value.ParseText( p, "-->", StrPair::COMMENT ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_COMMENT, start, 0 ); + } + return p; +} + + +XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? + return comment; +} + + +bool XMLComment::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLComment* comment = compare->ToComment(); + return ( comment && XMLUtil::StringEqual( comment->Value(), Value() )); +} + + +bool XMLComment::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + + +// --------- XMLDeclaration ---------- // + +XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLDeclaration::~XMLDeclaration() +{ + //printf( "~XMLDeclaration\n" ); +} + + +char* XMLDeclaration::ParseDeep( char* p, StrPair* ) +{ + // Declaration parses as text. + const char* start = p; + p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_DECLARATION, start, 0 ); + } + return p; +} + + +XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? + return dec; +} + + +bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLDeclaration* declaration = compare->ToDeclaration(); + return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() )); +} + + + +bool XMLDeclaration::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + +// --------- XMLUnknown ---------- // + +XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLUnknown::~XMLUnknown() +{ +} + + +char* XMLUnknown::ParseDeep( char* p, StrPair* ) +{ + // Unknown parses as text. + const char* start = p; + + p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_UNKNOWN, start, 0 ); + } + return p; +} + + +XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? + return text; +} + + +bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLUnknown* unknown = compare->ToUnknown(); + return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() )); +} + + +bool XMLUnknown::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + +// --------- XMLAttribute ---------- // + +const char* XMLAttribute::Name() const +{ + return _name.GetStr(); +} + +const char* XMLAttribute::Value() const +{ + return _value.GetStr(); +} + +char* XMLAttribute::ParseDeep( char* p, bool processEntities ) +{ + // Parse using the name rules: bug fix, was using ParseText before + p = _name.ParseName( p ); + if ( !p || !*p ) { + return 0; + } + + // Skip white space before = + p = XMLUtil::SkipWhiteSpace( p ); + if ( *p != '=' ) { + return 0; + } + + ++p; // move up to opening quote + p = XMLUtil::SkipWhiteSpace( p ); + if ( *p != '\"' && *p != '\'' ) { + return 0; + } + + char endTag[2] = { *p, 0 }; + ++p; // move past opening quote + + p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES ); + return p; +} + + +void XMLAttribute::SetName( const char* n ) +{ + _name.SetStr( n ); +} + + +XMLError XMLAttribute::QueryIntValue( int* value ) const +{ + if ( XMLUtil::ToInt( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const +{ + if ( XMLUtil::ToUnsigned( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryBoolValue( bool* value ) const +{ + if ( XMLUtil::ToBool( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryFloatValue( float* value ) const +{ + if ( XMLUtil::ToFloat( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryDoubleValue( double* value ) const +{ + if ( XMLUtil::ToDouble( Value(), value )) { + return XML_NO_ERROR; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +void XMLAttribute::SetAttribute( const char* v ) +{ + _value.SetStr( v ); +} + + +void XMLAttribute::SetAttribute( int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +void XMLAttribute::SetAttribute( unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +void XMLAttribute::SetAttribute( bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + +void XMLAttribute::SetAttribute( double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + +void XMLAttribute::SetAttribute( float v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +// --------- XMLElement ---------- // +XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), + _closingType( 0 ), + _rootAttribute( 0 ) +{ +} + + +XMLElement::~XMLElement() +{ + while( _rootAttribute ) { + XMLAttribute* next = _rootAttribute->_next; + DeleteAttribute( _rootAttribute ); + _rootAttribute = next; + } +} + + +const XMLAttribute* XMLElement::FindAttribute( const char* name ) const +{ + for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) { + if ( XMLUtil::StringEqual( a->Name(), name ) ) { + return a; + } + } + return 0; +} + + +const char* XMLElement::Attribute( const char* name, const char* value ) const +{ + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return 0; + } + if ( !value || XMLUtil::StringEqual( a->Value(), value )) { + return a->Value(); + } + return 0; +} + + +const char* XMLElement::GetText() const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + return FirstChild()->Value(); + } + return 0; +} + + +void XMLElement::SetText( const char* inText ) +{ + if ( FirstChild() && FirstChild()->ToText() ) + FirstChild()->SetValue( inText ); + else { + XMLText* theText = GetDocument()->NewText( inText ); + InsertFirstChild( theText ); + } +} + + +void XMLElement::SetText( int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( float v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +XMLError XMLElement::QueryIntText( int* ival ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToInt( t, ival ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToUnsigned( t, uval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryBoolText( bool* bval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToBool( t, bval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryDoubleText( double* dval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToDouble( t, dval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryFloatText( float* fval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToFloat( t, fval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + + +XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) +{ + XMLAttribute* last = 0; + XMLAttribute* attrib = 0; + for( attrib = _rootAttribute; + attrib; + last = attrib, attrib = attrib->_next ) { + if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { + break; + } + } + if ( !attrib ) { + TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); + attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); + attrib->_memPool = &_document->_attributePool; + if ( last ) { + last->_next = attrib; + } + else { + _rootAttribute = attrib; + } + attrib->SetName( name ); + attrib->_memPool->SetTracked(); // always created and linked. + } + return attrib; +} + + +void XMLElement::DeleteAttribute( const char* name ) +{ + XMLAttribute* prev = 0; + for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { + if ( XMLUtil::StringEqual( name, a->Name() ) ) { + if ( prev ) { + prev->_next = a->_next; + } + else { + _rootAttribute = a->_next; + } + DeleteAttribute( a ); + break; + } + prev = a; + } +} + + +char* XMLElement::ParseAttributes( char* p ) +{ + const char* start = p; + XMLAttribute* prevAttribute = 0; + + // Read the attributes. + while( p ) { + p = XMLUtil::SkipWhiteSpace( p ); + if ( !(*p) ) { + _document->SetError( XML_ERROR_PARSING_ELEMENT, start, Name() ); + return 0; + } + + // attribute. + if (XMLUtil::IsNameStartChar( *p ) ) { + TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); + XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); + attrib->_memPool = &_document->_attributePool; + attrib->_memPool->SetTracked(); + + p = attrib->ParseDeep( p, _document->ProcessEntities() ); + if ( !p || Attribute( attrib->Name() ) ) { + DeleteAttribute( attrib ); + _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, start, p ); + return 0; + } + // There is a minor bug here: if the attribute in the source xml + // document is duplicated, it will not be detected and the + // attribute will be doubly added. However, tracking the 'prevAttribute' + // avoids re-scanning the attribute list. Preferring performance for + // now, may reconsider in the future. + if ( prevAttribute ) { + prevAttribute->_next = attrib; + } + else { + _rootAttribute = attrib; + } + prevAttribute = attrib; + } + // end of the tag + else if ( *p == '>' ) { + ++p; + break; + } + // end of the tag + else if ( *p == '/' && *(p+1) == '>' ) { + _closingType = CLOSED; + return p+2; // done; sealed element. + } + else { + _document->SetError( XML_ERROR_PARSING_ELEMENT, start, p ); + return 0; + } + } + return p; +} + +void XMLElement::DeleteAttribute( XMLAttribute* attribute ) +{ + if ( attribute == 0 ) { + return; + } + MemPool* pool = attribute->_memPool; + attribute->~XMLAttribute(); + pool->Free( attribute ); +} + +// +// +// foobar +// +char* XMLElement::ParseDeep( char* p, StrPair* strPair ) +{ + // Read the element name. + p = XMLUtil::SkipWhiteSpace( p ); + + // The closing element is the form. It is + // parsed just like a regular element then deleted from + // the DOM. + if ( *p == '/' ) { + _closingType = CLOSING; + ++p; + } + + p = _value.ParseName( p ); + if ( _value.Empty() ) { + return 0; + } + + p = ParseAttributes( p ); + if ( !p || !*p || _closingType ) { + return p; + } + + p = XMLNode::ParseDeep( p, strPair ); + return p; +} + + + +XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? + for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { + element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? + } + return element; +} + + +bool XMLElement::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLElement* other = compare->ToElement(); + if ( other && XMLUtil::StringEqual( other->Name(), Name() )) { + + const XMLAttribute* a=FirstAttribute(); + const XMLAttribute* b=other->FirstAttribute(); + + while ( a && b ) { + if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { + return false; + } + a = a->Next(); + b = b->Next(); + } + if ( a || b ) { + // different count + return false; + } + return true; + } + return false; +} + + +bool XMLElement::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + if ( visitor->VisitEnter( *this, _rootAttribute ) ) { + for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) { + break; + } + } + } + return visitor->VisitExit( *this ); +} + + +// --------- XMLDocument ----------- // + +// Warning: List must match 'enum XMLError' +const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { + "XML_SUCCESS", + "XML_NO_ATTRIBUTE", + "XML_WRONG_ATTRIBUTE_TYPE", + "XML_ERROR_FILE_NOT_FOUND", + "XML_ERROR_FILE_COULD_NOT_BE_OPENED", + "XML_ERROR_FILE_READ_ERROR", + "XML_ERROR_ELEMENT_MISMATCH", + "XML_ERROR_PARSING_ELEMENT", + "XML_ERROR_PARSING_ATTRIBUTE", + "XML_ERROR_IDENTIFYING_TAG", + "XML_ERROR_PARSING_TEXT", + "XML_ERROR_PARSING_CDATA", + "XML_ERROR_PARSING_COMMENT", + "XML_ERROR_PARSING_DECLARATION", + "XML_ERROR_PARSING_UNKNOWN", + "XML_ERROR_EMPTY_DOCUMENT", + "XML_ERROR_MISMATCHED_ELEMENT", + "XML_ERROR_PARSING", + "XML_CAN_NOT_CONVERT_TEXT", + "XML_NO_TEXT_NODE" +}; + + +XMLDocument::XMLDocument( bool processEntities, Whitespace whitespace ) : + XMLNode( 0 ), + _writeBOM( false ), + _processEntities( processEntities ), + _errorID( XML_NO_ERROR ), + _whitespace( whitespace ), + _errorStr1( 0 ), + _errorStr2( 0 ), + _charBuffer( 0 ) +{ + // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) + _document = this; +} + + +XMLDocument::~XMLDocument() +{ + Clear(); +} + + +void XMLDocument::Clear() +{ + DeleteChildren(); + +#ifdef DEBUG + const bool hadError = Error(); +#endif + _errorID = XML_NO_ERROR; + _errorStr1 = 0; + _errorStr2 = 0; + + delete [] _charBuffer; + _charBuffer = 0; + +#if 0 + _textPool.Trace( "text" ); + _elementPool.Trace( "element" ); + _commentPool.Trace( "comment" ); + _attributePool.Trace( "attribute" ); +#endif + +#ifdef DEBUG + if ( !hadError ) { + TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); + TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); + TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); + TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); + } +#endif +} + + +XMLElement* XMLDocument::NewElement( const char* name ) +{ + TIXMLASSERT( sizeof( XMLElement ) == _elementPool.ItemSize() ); + XMLElement* ele = new (_elementPool.Alloc()) XMLElement( this ); + ele->_memPool = &_elementPool; + ele->SetName( name ); + return ele; +} + + +XMLComment* XMLDocument::NewComment( const char* str ) +{ + TIXMLASSERT( sizeof( XMLComment ) == _commentPool.ItemSize() ); + XMLComment* comment = new (_commentPool.Alloc()) XMLComment( this ); + comment->_memPool = &_commentPool; + comment->SetValue( str ); + return comment; +} + + +XMLText* XMLDocument::NewText( const char* str ) +{ + TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() ); + XMLText* text = new (_textPool.Alloc()) XMLText( this ); + text->_memPool = &_textPool; + text->SetValue( str ); + return text; +} + + +XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) +{ + TIXMLASSERT( sizeof( XMLDeclaration ) == _commentPool.ItemSize() ); + XMLDeclaration* dec = new (_commentPool.Alloc()) XMLDeclaration( this ); + dec->_memPool = &_commentPool; + dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); + return dec; +} + + +XMLUnknown* XMLDocument::NewUnknown( const char* str ) +{ + TIXMLASSERT( sizeof( XMLUnknown ) == _commentPool.ItemSize() ); + XMLUnknown* unk = new (_commentPool.Alloc()) XMLUnknown( this ); + unk->_memPool = &_commentPool; + unk->SetValue( str ); + return unk; +} + +static FILE* callfopen( const char* filepath, const char* mode ) +{ + TIXMLASSERT( filepath ); + TIXMLASSERT( mode ); +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) + FILE* fp = 0; + errno_t err = fopen_s( &fp, filepath, mode ); + if ( err ) { + return 0; + } +#else + FILE* fp = fopen( filepath, mode ); +#endif + return fp; +} + +void XMLDocument::DeleteNode( XMLNode* node ) { + TIXMLASSERT( node ); + TIXMLASSERT(node->_document == this ); + if (node->_parent) { + node->_parent->DeleteChild( node ); + } + else { + // Isn't in the tree. + // Use the parent delete. + // Also, we need to mark it tracked: we 'know' + // it was never used. + node->_memPool->SetTracked(); + // Call the static XMLNode version: + XMLNode::DeleteNode(node); + } +} + + +XMLError XMLDocument::LoadFile( const char* filename ) +{ + Clear(); + FILE* fp = callfopen( filename, "rb" ); + if ( !fp ) { + SetError( XML_ERROR_FILE_NOT_FOUND, filename, 0 ); + return _errorID; + } + LoadFile( fp ); + fclose( fp ); + return _errorID; +} + +// This is likely overengineered template art to have a check that unsigned long value incremented +// by one still fits into size_t. If size_t type is larger than unsigned long type +// (x86_64-w64-mingw32 target) then the check is redundant and gcc and clang emit +// -Wtype-limits warning. This piece makes the compiler select code with a check when a check +// is useful and code with no check when a check is redundant depending on how size_t and unsigned long +// types sizes relate to each other. +template += sizeof(size_t))> +struct LongFitsIntoSizeTMinusOne { + static bool Fits( unsigned long value ) + { + return value < (size_t)-1; + } +}; + +template <> +bool LongFitsIntoSizeTMinusOne::Fits( unsigned long /*value*/ ) +{ + return true; +} + +XMLError XMLDocument::LoadFile( FILE* fp ) +{ + Clear(); + + fseek( fp, 0, SEEK_SET ); + if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + fseek( fp, 0, SEEK_END ); + const long filelength = ftell( fp ); + fseek( fp, 0, SEEK_SET ); + if ( filelength == -1L ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + TIXMLASSERT( filelength >= 0 ); + + if ( !LongFitsIntoSizeTMinusOne<>::Fits( filelength ) ) { + // Cannot handle files which won't fit in buffer together with null terminator + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + if ( filelength == 0 ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + + const size_t size = filelength; + TIXMLASSERT( _charBuffer == 0 ); + _charBuffer = new char[size+1]; + size_t read = fread( _charBuffer, 1, size, fp ); + if ( read != size ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + _charBuffer[size] = 0; + + Parse(); + return _errorID; +} + + +XMLError XMLDocument::SaveFile( const char* filename, bool compact ) +{ + FILE* fp = callfopen( filename, "w" ); + if ( !fp ) { + SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, filename, 0 ); + return _errorID; + } + SaveFile(fp, compact); + fclose( fp ); + return _errorID; +} + + +XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) +{ + // Clear any error from the last save, otherwise it will get reported + // for *this* call. + SetError( XML_NO_ERROR, 0, 0 ); + XMLPrinter stream( fp, compact ); + Print( &stream ); + return _errorID; +} + + +XMLError XMLDocument::Parse( const char* p, size_t len ) +{ + Clear(); + + if ( len == 0 || !p || !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + if ( len == (size_t)(-1) ) { + len = strlen( p ); + } + TIXMLASSERT( _charBuffer == 0 ); + _charBuffer = new char[ len+1 ]; + memcpy( _charBuffer, p, len ); + _charBuffer[len] = 0; + + Parse(); + if ( Error() ) { + // clean up now essentially dangling memory. + // and the parse fail can put objects in the + // pools that are dead and inaccessible. + DeleteChildren(); + _elementPool.Clear(); + _attributePool.Clear(); + _textPool.Clear(); + _commentPool.Clear(); + } + return _errorID; +} + + +void XMLDocument::Print( XMLPrinter* streamer ) const +{ + if ( streamer ) { + Accept( streamer ); + } + else { + XMLPrinter stdoutStreamer( stdout ); + Accept( &stdoutStreamer ); + } +} + + +void XMLDocument::SetError( XMLError error, const char* str1, const char* str2 ) +{ + TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT ); + _errorID = error; + _errorStr1 = str1; + _errorStr2 = str2; +} + +const char* XMLDocument::ErrorName() const +{ + TIXMLASSERT( _errorID >= 0 && _errorID < XML_ERROR_COUNT ); + const char* errorName = _errorNames[_errorID]; + TIXMLASSERT( errorName && errorName[0] ); + return errorName; +} + +void XMLDocument::PrintError() const +{ + if ( Error() ) { + static const int LEN = 20; + char buf1[LEN] = { 0 }; + char buf2[LEN] = { 0 }; + + if ( _errorStr1 ) { + TIXML_SNPRINTF( buf1, LEN, "%s", _errorStr1 ); + } + if ( _errorStr2 ) { + TIXML_SNPRINTF( buf2, LEN, "%s", _errorStr2 ); + } + + // Should check INT_MIN <= _errorID && _errorId <= INT_MAX, but that + // causes a clang "always true" -Wtautological-constant-out-of-range-compare warning + TIXMLASSERT( 0 <= _errorID && XML_ERROR_COUNT - 1 <= INT_MAX ); + printf( "XMLDocument error id=%d '%s' str1=%s str2=%s\n", + static_cast( _errorID ), ErrorName(), buf1, buf2 ); + } +} + +void XMLDocument::Parse() +{ + TIXMLASSERT( NoChildren() ); // Clear() must have been called previously + TIXMLASSERT( _charBuffer ); + char* p = _charBuffer; + p = XMLUtil::SkipWhiteSpace( p ); + p = const_cast( XMLUtil::ReadBOM( p, &_writeBOM ) ); + if ( !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return; + } + ParseDeep(p, 0 ); +} + +XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) : + _elementJustOpened( false ), + _firstElement( true ), + _fp( file ), + _depth( depth ), + _textDepth( -1 ), + _processEntities( true ), + _compactMode( compact ) +{ + for( int i=0; i'] = true; // not required, but consistency is nice + _buffer.Push( 0 ); +} + + +void XMLPrinter::Print( const char* format, ... ) +{ + va_list va; + va_start( va, format ); + + if ( _fp ) { + vfprintf( _fp, format, va ); + } + else { + const int len = TIXML_VSCPRINTF( format, va ); + // Close out and re-start the va-args + va_end( va ); + TIXMLASSERT( len >= 0 ); + va_start( va, format ); + TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 ); + char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator. + TIXML_VSNPRINTF( p, len+1, format, va ); + } + va_end( va ); +} + + +void XMLPrinter::PrintSpace( int depth ) +{ + for( int i=0; i 0 && *q < ENTITY_RANGE ) { + // Check for entities. If one is found, flush + // the stream up until the entity, write the + // entity, and keep looking. + if ( flag[(unsigned char)(*q)] ) { + while ( p < q ) { + const size_t delta = q - p; + // %.*s accepts type int as "precision" + const int toPrint = ( INT_MAX < delta ) ? INT_MAX : (int)delta; + Print( "%.*s", toPrint, p ); + p += toPrint; + } + bool entityPatternPrinted = false; + for( int i=0; i" ); + } + else { + if ( _textDepth < 0 && !compactMode) { + Print( "\n" ); + PrintSpace( _depth ); + } + Print( "", name ); + } + + if ( _textDepth == _depth ) { + _textDepth = -1; + } + if ( _depth == 0 && !compactMode) { + Print( "\n" ); + } + _elementJustOpened = false; +} + + +void XMLPrinter::SealElementIfJustOpened() +{ + if ( !_elementJustOpened ) { + return; + } + _elementJustOpened = false; + Print( ">" ); +} + + +void XMLPrinter::PushText( const char* text, bool cdata ) +{ + _textDepth = _depth-1; + + SealElementIfJustOpened(); + if ( cdata ) { + Print( "", text ); + } + else { + PrintString( text, true ); + } +} + +void XMLPrinter::PushText( int value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( unsigned value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( bool value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( float value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( double value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushComment( const char* comment ) +{ + SealElementIfJustOpened(); + if ( _textDepth < 0 && !_firstElement && !_compactMode) { + Print( "\n" ); + PrintSpace( _depth ); + } + _firstElement = false; + Print( "", comment ); +} + + +void XMLPrinter::PushDeclaration( const char* value ) +{ + SealElementIfJustOpened(); + if ( _textDepth < 0 && !_firstElement && !_compactMode) { + Print( "\n" ); + PrintSpace( _depth ); + } + _firstElement = false; + Print( "", value ); +} + + +void XMLPrinter::PushUnknown( const char* value ) +{ + SealElementIfJustOpened(); + if ( _textDepth < 0 && !_firstElement && !_compactMode) { + Print( "\n" ); + PrintSpace( _depth ); + } + _firstElement = false; + Print( "", value ); +} + + +bool XMLPrinter::VisitEnter( const XMLDocument& doc ) +{ + _processEntities = doc.ProcessEntities(); + if ( doc.HasBOM() ) { + PushHeader( true, false ); + } + return true; +} + + +bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) +{ + const XMLElement* parentElem = 0; + if ( element.Parent() ) { + parentElem = element.Parent()->ToElement(); + } + const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode; + OpenElement( element.Name(), compactMode ); + while ( attribute ) { + PushAttribute( attribute->Name(), attribute->Value() ); + attribute = attribute->Next(); + } + return true; +} + + +bool XMLPrinter::VisitExit( const XMLElement& element ) +{ + CloseElement( CompactMode(element) ); + return true; +} + + +bool XMLPrinter::Visit( const XMLText& text ) +{ + PushText( text.Value(), text.CData() ); + return true; +} + + +bool XMLPrinter::Visit( const XMLComment& comment ) +{ + PushComment( comment.Value() ); + return true; +} + +bool XMLPrinter::Visit( const XMLDeclaration& declaration ) +{ + PushDeclaration( declaration.Value() ); + return true; +} + + +bool XMLPrinter::Visit( const XMLUnknown& unknown ) +{ + PushUnknown( unknown.Value() ); + return true; +} + +} // namespace tinyxml2 + diff --git a/lib/tinyxml/tinyxml2.h b/lib/tinyxml/tinyxml2.h new file mode 100644 index 0000000..fb7464a --- /dev/null +++ b/lib/tinyxml/tinyxml2.h @@ -0,0 +1,2102 @@ +/* +Original code by Lee Thomason (www.grinninglizard.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#ifndef TINYXML2_INCLUDED +#define TINYXML2_INCLUDED + +#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) +# include +# include +# include +# include +# include +#else +# include +# include +# include +# include +# include +#endif + +/* + TODO: intern strings instead of allocation. +*/ +/* + gcc: + g++ -Wall -DDEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe + + Formatting, Artistic Style: + AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h +*/ + +#if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__) +# ifndef DEBUG +# define DEBUG +# endif +#endif + +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4251) +#endif + +#ifdef _WIN32 +# ifdef TINYXML2_EXPORT +# define TINYXML2_LIB __declspec(dllexport) +# elif defined(TINYXML2_IMPORT) +# define TINYXML2_LIB __declspec(dllimport) +# else +# define TINYXML2_LIB +# endif +#else +# define TINYXML2_LIB +#endif + + +#if defined(DEBUG) +# if defined(_MSC_VER) +# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like +# define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); } +# elif defined (ANDROID_NDK) +# include +# define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } +# else +# include +# define TIXMLASSERT assert +# endif +#else +# define TIXMLASSERT( x ) {} +#endif + + +/* Versioning, past 1.0.14: + http://semver.org/ +*/ +static const int TIXML2_MAJOR_VERSION = 3; +static const int TIXML2_MINOR_VERSION = 0; +static const int TIXML2_PATCH_VERSION = 0; + +namespace tinyxml2 +{ +class XMLDocument; +class XMLElement; +class XMLAttribute; +class XMLComment; +class XMLText; +class XMLDeclaration; +class XMLUnknown; +class XMLPrinter; + +/* + A class that wraps strings. Normally stores the start and end + pointers into the XML file itself, and will apply normalization + and entity translation if actually read. Can also store (and memory + manage) a traditional char[] +*/ +class StrPair +{ +public: + enum { + NEEDS_ENTITY_PROCESSING = 0x01, + NEEDS_NEWLINE_NORMALIZATION = 0x02, + NEEDS_WHITESPACE_COLLAPSING = 0x04, + + TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_NAME = 0, + ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + COMMENT = NEEDS_NEWLINE_NORMALIZATION + }; + + StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} + ~StrPair(); + + void Set( char* start, char* end, int flags ) { + Reset(); + _start = start; + _end = end; + _flags = flags | NEEDS_FLUSH; + } + + const char* GetStr(); + + bool Empty() const { + return _start == _end; + } + + void SetInternedStr( const char* str ) { + Reset(); + _start = const_cast(str); + } + + void SetStr( const char* str, int flags=0 ); + + char* ParseText( char* in, const char* endTag, int strFlags ); + char* ParseName( char* in ); + + void TransferTo( StrPair* other ); + +private: + void Reset(); + void CollapseWhitespace(); + + enum { + NEEDS_FLUSH = 0x100, + NEEDS_DELETE = 0x200 + }; + + int _flags; + char* _start; + char* _end; + + StrPair( const StrPair& other ); // not supported + void operator=( StrPair& other ); // not supported, use TransferTo() +}; + + +/* + A dynamic array of Plain Old Data. Doesn't support constructors, etc. + Has a small initial memory pool, so that low or no usage will not + cause a call to new/delete +*/ +template +class DynArray +{ +public: + DynArray() { + _mem = _pool; + _allocated = INITIAL_SIZE; + _size = 0; + } + + ~DynArray() { + if ( _mem != _pool ) { + delete [] _mem; + } + } + + void Clear() { + _size = 0; + } + + void Push( T t ) { + TIXMLASSERT( _size < INT_MAX ); + EnsureCapacity( _size+1 ); + _mem[_size++] = t; + } + + T* PushArr( int count ) { + TIXMLASSERT( count >= 0 ); + TIXMLASSERT( _size <= INT_MAX - count ); + EnsureCapacity( _size+count ); + T* ret = &_mem[_size]; + _size += count; + return ret; + } + + T Pop() { + TIXMLASSERT( _size > 0 ); + return _mem[--_size]; + } + + void PopArr( int count ) { + TIXMLASSERT( _size >= count ); + _size -= count; + } + + bool Empty() const { + return _size == 0; + } + + T& operator[](int i) { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + const T& operator[](int i) const { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + const T& PeekTop() const { + TIXMLASSERT( _size > 0 ); + return _mem[ _size - 1]; + } + + int Size() const { + TIXMLASSERT( _size >= 0 ); + return _size; + } + + int Capacity() const { + TIXMLASSERT( _allocated >= INITIAL_SIZE ); + return _allocated; + } + + const T* Mem() const { + TIXMLASSERT( _mem ); + return _mem; + } + + T* Mem() { + TIXMLASSERT( _mem ); + return _mem; + } + +private: + DynArray( const DynArray& ); // not supported + void operator=( const DynArray& ); // not supported + + void EnsureCapacity( int cap ) { + TIXMLASSERT( cap > 0 ); + if ( cap > _allocated ) { + TIXMLASSERT( cap <= INT_MAX / 2 ); + int newAllocated = cap * 2; + T* newMem = new T[newAllocated]; + memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs + if ( _mem != _pool ) { + delete [] _mem; + } + _mem = newMem; + _allocated = newAllocated; + } + } + + T* _mem; + T _pool[INITIAL_SIZE]; + int _allocated; // objects allocated + int _size; // number objects in use +}; + + +/* + Parent virtual class of a pool for fast allocation + and deallocation of objects. +*/ +class MemPool +{ +public: + MemPool() {} + virtual ~MemPool() {} + + virtual int ItemSize() const = 0; + virtual void* Alloc() = 0; + virtual void Free( void* ) = 0; + virtual void SetTracked() = 0; + virtual void Clear() = 0; +}; + + +/* + Template child class to create pools of the correct type. +*/ +template< int SIZE > +class MemPoolT : public MemPool +{ +public: + MemPoolT() : _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} + ~MemPoolT() { + Clear(); + } + + void Clear() { + // Delete the blocks. + while( !_blockPtrs.Empty()) { + Block* b = _blockPtrs.Pop(); + delete b; + } + _root = 0; + _currentAllocs = 0; + _nAllocs = 0; + _maxAllocs = 0; + _nUntracked = 0; + } + + virtual int ItemSize() const { + return SIZE; + } + int CurrentAllocs() const { + return _currentAllocs; + } + + virtual void* Alloc() { + if ( !_root ) { + // Need a new block. + Block* block = new Block(); + _blockPtrs.Push( block ); + + for( int i=0; ichunk[i].next = &block->chunk[i+1]; + } + block->chunk[COUNT-1].next = 0; + _root = block->chunk; + } + void* result = _root; + _root = _root->next; + + ++_currentAllocs; + if ( _currentAllocs > _maxAllocs ) { + _maxAllocs = _currentAllocs; + } + _nAllocs++; + _nUntracked++; + return result; + } + + virtual void Free( void* mem ) { + if ( !mem ) { + return; + } + --_currentAllocs; + Chunk* chunk = static_cast( mem ); +#ifdef DEBUG + memset( chunk, 0xfe, sizeof(Chunk) ); +#endif + chunk->next = _root; + _root = chunk; + } + void Trace( const char* name ) { + printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", + name, _maxAllocs, _maxAllocs*SIZE/1024, _currentAllocs, SIZE, _nAllocs, _blockPtrs.Size() ); + } + + void SetTracked() { + _nUntracked--; + } + + int Untracked() const { + return _nUntracked; + } + + // This number is perf sensitive. 4k seems like a good tradeoff on my machine. + // The test file is large, 170k. + // Release: VS2010 gcc(no opt) + // 1k: 4000 + // 2k: 4000 + // 4k: 3900 21000 + // 16k: 5200 + // 32k: 4300 + // 64k: 4000 21000 + enum { COUNT = (4*1024)/SIZE }; // Some compilers do not accept to use COUNT in private part if COUNT is private + +private: + MemPoolT( const MemPoolT& ); // not supported + void operator=( const MemPoolT& ); // not supported + + union Chunk { + Chunk* next; + char mem[SIZE]; + }; + struct Block { + Chunk chunk[COUNT]; + }; + DynArray< Block*, 10 > _blockPtrs; + Chunk* _root; + + int _currentAllocs; + int _nAllocs; + int _maxAllocs; + int _nUntracked; +}; + + + +/** + Implements the interface to the "Visitor pattern" (see the Accept() method.) + If you call the Accept() method, it requires being passed a XMLVisitor + class to handle callbacks. For nodes that contain other nodes (Document, Element) + you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs + are simply called with Visit(). + + If you return 'true' from a Visit method, recursive parsing will continue. If you return + false, no children of this node or its siblings will be visited. + + All flavors of Visit methods have a default implementation that returns 'true' (continue + visiting). You need to only override methods that are interesting to you. + + Generally Accept() is called on the XMLDocument, although all nodes support visiting. + + You should never change the document from a callback. + + @sa XMLNode::Accept() +*/ +class TINYXML2_LIB XMLVisitor +{ +public: + virtual ~XMLVisitor() {} + + /// Visit a document. + virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { + return true; + } + /// Visit a document. + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + /// Visit an element. + virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { + return true; + } + /// Visit an element. + virtual bool VisitExit( const XMLElement& /*element*/ ) { + return true; + } + + /// Visit a declaration. + virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { + return true; + } + /// Visit a text node. + virtual bool Visit( const XMLText& /*text*/ ) { + return true; + } + /// Visit a comment node. + virtual bool Visit( const XMLComment& /*comment*/ ) { + return true; + } + /// Visit an unknown node. + virtual bool Visit( const XMLUnknown& /*unknown*/ ) { + return true; + } +}; + +// WARNING: must match XMLDocument::_errorNames[] +enum XMLError { + XML_SUCCESS = 0, + XML_NO_ERROR = 0, + XML_NO_ATTRIBUTE, + XML_WRONG_ATTRIBUTE_TYPE, + XML_ERROR_FILE_NOT_FOUND, + XML_ERROR_FILE_COULD_NOT_BE_OPENED, + XML_ERROR_FILE_READ_ERROR, + XML_ERROR_ELEMENT_MISMATCH, + XML_ERROR_PARSING_ELEMENT, + XML_ERROR_PARSING_ATTRIBUTE, + XML_ERROR_IDENTIFYING_TAG, + XML_ERROR_PARSING_TEXT, + XML_ERROR_PARSING_CDATA, + XML_ERROR_PARSING_COMMENT, + XML_ERROR_PARSING_DECLARATION, + XML_ERROR_PARSING_UNKNOWN, + XML_ERROR_EMPTY_DOCUMENT, + XML_ERROR_MISMATCHED_ELEMENT, + XML_ERROR_PARSING, + XML_CAN_NOT_CONVERT_TEXT, + XML_NO_TEXT_NODE, + + XML_ERROR_COUNT +}; + + +/* + Utility functionality. +*/ +class XMLUtil +{ +public: + static const char* SkipWhiteSpace( const char* p ) { + TIXMLASSERT( p ); + while( IsWhiteSpace(*p) ) { + ++p; + } + TIXMLASSERT( p ); + return p; + } + static char* SkipWhiteSpace( char* p ) { + return const_cast( SkipWhiteSpace( const_cast(p) ) ); + } + + // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't + // correct, but simple, and usually works. + static bool IsWhiteSpace( char p ) { + return !IsUTF8Continuation(p) && isspace( static_cast(p) ); + } + + inline static bool IsNameStartChar( unsigned char ch ) { + if ( ch >= 128 ) { + // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() + return true; + } + if ( isalpha( ch ) ) { + return true; + } + return ch == ':' || ch == '_'; + } + + inline static bool IsNameChar( unsigned char ch ) { + return IsNameStartChar( ch ) + || isdigit( ch ) + || ch == '.' + || ch == '-'; + } + + inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { + if ( p == q ) { + return true; + } + return strncmp( p, q, nChar ) == 0; + } + + inline static bool IsUTF8Continuation( char p ) { + return ( p & 0x80 ) != 0; + } + + static const char* ReadBOM( const char* p, bool* hasBOM ); + // p is the starting location, + // the UTF-8 value of the entity will be placed in value, and length filled in. + static const char* GetCharacterRef( const char* p, char* value, int* length ); + static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); + + // converts primitive types to strings + static void ToStr( int v, char* buffer, int bufferSize ); + static void ToStr( unsigned v, char* buffer, int bufferSize ); + static void ToStr( bool v, char* buffer, int bufferSize ); + static void ToStr( float v, char* buffer, int bufferSize ); + static void ToStr( double v, char* buffer, int bufferSize ); + + // converts strings to primitive types + static bool ToInt( const char* str, int* value ); + static bool ToUnsigned( const char* str, unsigned* value ); + static bool ToBool( const char* str, bool* value ); + static bool ToFloat( const char* str, float* value ); + static bool ToDouble( const char* str, double* value ); +}; + + +/** XMLNode is a base class for every object that is in the + XML Document Object Model (DOM), except XMLAttributes. + Nodes have siblings, a parent, and children which can + be navigated. A node is always in a XMLDocument. + The type of a XMLNode can be queried, and it can + be cast to its more defined type. + + A XMLDocument allocates memory for all its Nodes. + When the XMLDocument gets deleted, all its Nodes + will also be deleted. + + @verbatim + A Document can contain: Element (container or leaf) + Comment (leaf) + Unknown (leaf) + Declaration( leaf ) + + An Element can contain: Element (container or leaf) + Text (leaf) + Attributes (not on tree) + Comment (leaf) + Unknown (leaf) + + @endverbatim +*/ +class TINYXML2_LIB XMLNode +{ + friend class XMLDocument; + friend class XMLElement; +public: + + /// Get the XMLDocument that owns this XMLNode. + const XMLDocument* GetDocument() const { + TIXMLASSERT( _document ); + return _document; + } + /// Get the XMLDocument that owns this XMLNode. + XMLDocument* GetDocument() { + TIXMLASSERT( _document ); + return _document; + } + + /// Safely cast to an Element, or null. + virtual XMLElement* ToElement() { + return 0; + } + /// Safely cast to Text, or null. + virtual XMLText* ToText() { + return 0; + } + /// Safely cast to a Comment, or null. + virtual XMLComment* ToComment() { + return 0; + } + /// Safely cast to a Document, or null. + virtual XMLDocument* ToDocument() { + return 0; + } + /// Safely cast to a Declaration, or null. + virtual XMLDeclaration* ToDeclaration() { + return 0; + } + /// Safely cast to an Unknown, or null. + virtual XMLUnknown* ToUnknown() { + return 0; + } + + virtual const XMLElement* ToElement() const { + return 0; + } + virtual const XMLText* ToText() const { + return 0; + } + virtual const XMLComment* ToComment() const { + return 0; + } + virtual const XMLDocument* ToDocument() const { + return 0; + } + virtual const XMLDeclaration* ToDeclaration() const { + return 0; + } + virtual const XMLUnknown* ToUnknown() const { + return 0; + } + + /** The meaning of 'value' changes for the specific type. + @verbatim + Document: empty (NULL is returned, not an empty string) + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim + */ + const char* Value() const; + + /** Set the Value of an XML node. + @sa Value() + */ + void SetValue( const char* val, bool staticMem=false ); + + /// Get the parent of this node on the DOM. + const XMLNode* Parent() const { + return _parent; + } + + XMLNode* Parent() { + return _parent; + } + + /// Returns true if this node has no children. + bool NoChildren() const { + return !_firstChild; + } + + /// Get the first child node, or null if none exists. + const XMLNode* FirstChild() const { + return _firstChild; + } + + XMLNode* FirstChild() { + return _firstChild; + } + + /** Get the first child element, or optionally the first child + element with the specified name. + */ + const XMLElement* FirstChildElement( const char* name = 0 ) const; + + XMLElement* FirstChildElement( const char* name = 0 ) { + return const_cast(const_cast(this)->FirstChildElement( name )); + } + + /// Get the last child node, or null if none exists. + const XMLNode* LastChild() const { + return _lastChild; + } + + XMLNode* LastChild() { + return _lastChild; + } + + /** Get the last child element or optionally the last child + element with the specified name. + */ + const XMLElement* LastChildElement( const char* name = 0 ) const; + + XMLElement* LastChildElement( const char* name = 0 ) { + return const_cast(const_cast(this)->LastChildElement(name) ); + } + + /// Get the previous (left) sibling node of this node. + const XMLNode* PreviousSibling() const { + return _prev; + } + + XMLNode* PreviousSibling() { + return _prev; + } + + /// Get the previous (left) sibling element of this node, with an optionally supplied name. + const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; + + XMLElement* PreviousSiblingElement( const char* name = 0 ) { + return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); + } + + /// Get the next (right) sibling node of this node. + const XMLNode* NextSibling() const { + return _next; + } + + XMLNode* NextSibling() { + return _next; + } + + /// Get the next (right) sibling element of this node, with an optionally supplied name. + const XMLElement* NextSiblingElement( const char* name = 0 ) const; + + XMLElement* NextSiblingElement( const char* name = 0 ) { + return const_cast(const_cast(this)->NextSiblingElement( name ) ); + } + + /** + Add a child node as the last (right) child. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the node does not + belong to the same document. + */ + XMLNode* InsertEndChild( XMLNode* addThis ); + + XMLNode* LinkEndChild( XMLNode* addThis ) { + return InsertEndChild( addThis ); + } + /** + Add a child node as the first (left) child. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the node does not + belong to the same document. + */ + XMLNode* InsertFirstChild( XMLNode* addThis ); + /** + Add a node after the specified child node. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the afterThis node + is not a child of this node, or if the node does not + belong to the same document. + */ + XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); + + /** + Delete all the children of this node. + */ + void DeleteChildren(); + + /** + Delete a child of this node. + */ + void DeleteChild( XMLNode* node ); + + /** + Make a copy of this node, but not its children. + You may pass in a Document pointer that will be + the owner of the new Node. If the 'document' is + null, then the node returned will be allocated + from the current Document. (this->GetDocument()) + + Note: if called on a XMLDocument, this will return null. + */ + virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; + + /** + Test if 2 nodes are the same, but don't test children. + The 2 nodes do not need to be in the same Document. + + Note: if called on a XMLDocument, this will return false. + */ + virtual bool ShallowEqual( const XMLNode* compare ) const = 0; + + /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the + XML tree will be conditionally visited and the host will be called back + via the XMLVisitor interface. + + This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse + the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this + interface versus any other.) + + The interface has been based on ideas from: + + - http://www.saxproject.org/ + - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + + Which are both good references for "visiting". + + An example of using Accept(): + @verbatim + XMLPrinter printer; + tinyxmlDoc.Accept( &printer ); + const char* xmlcstr = printer.CStr(); + @endverbatim + */ + virtual bool Accept( XMLVisitor* visitor ) const = 0; + +protected: + XMLNode( XMLDocument* ); + virtual ~XMLNode(); + + virtual char* ParseDeep( char*, StrPair* ); + + XMLDocument* _document; + XMLNode* _parent; + mutable StrPair _value; + + XMLNode* _firstChild; + XMLNode* _lastChild; + + XMLNode* _prev; + XMLNode* _next; + +private: + MemPool* _memPool; + void Unlink( XMLNode* child ); + static void DeleteNode( XMLNode* node ); + void InsertChildPreamble( XMLNode* insertThis ) const; + + XMLNode( const XMLNode& ); // not supported + XMLNode& operator=( const XMLNode& ); // not supported +}; + + +/** XML text. + + Note that a text node can have child element nodes, for example: + @verbatim + This is bold + @endverbatim + + A text node can have 2 ways to output the next. "normal" output + and CDATA. It will default to the mode it was parsed from the XML file and + you generally want to leave it alone, but you can change the output mode with + SetCData() and query it with CData(). +*/ +class TINYXML2_LIB XMLText : public XMLNode +{ + friend class XMLBase; + friend class XMLDocument; +public: + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLText* ToText() { + return this; + } + virtual const XMLText* ToText() const { + return this; + } + + /// Declare whether this should be CDATA or standard text. + void SetCData( bool isCData ) { + _isCData = isCData; + } + /// Returns true if this is a CDATA text element. + bool CData() const { + return _isCData; + } + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} + virtual ~XMLText() {} + + char* ParseDeep( char*, StrPair* endTag ); + +private: + bool _isCData; + + XMLText( const XMLText& ); // not supported + XMLText& operator=( const XMLText& ); // not supported +}; + + +/** An XML Comment. */ +class TINYXML2_LIB XMLComment : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLComment* ToComment() { + return this; + } + virtual const XMLComment* ToComment() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + XMLComment( XMLDocument* doc ); + virtual ~XMLComment(); + + char* ParseDeep( char*, StrPair* endTag ); + +private: + XMLComment( const XMLComment& ); // not supported + XMLComment& operator=( const XMLComment& ); // not supported +}; + + +/** In correct XML the declaration is the first entry in the file. + @verbatim + + @endverbatim + + TinyXML-2 will happily read or write files without a declaration, + however. + + The text of the declaration isn't interpreted. It is parsed + and written as a string. +*/ +class TINYXML2_LIB XMLDeclaration : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLDeclaration* ToDeclaration() { + return this; + } + virtual const XMLDeclaration* ToDeclaration() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + XMLDeclaration( XMLDocument* doc ); + virtual ~XMLDeclaration(); + + char* ParseDeep( char*, StrPair* endTag ); + +private: + XMLDeclaration( const XMLDeclaration& ); // not supported + XMLDeclaration& operator=( const XMLDeclaration& ); // not supported +}; + + +/** Any tag that TinyXML-2 doesn't recognize is saved as an + unknown. It is a tag of text, but should not be modified. + It will be written back to the XML, unchanged, when the file + is saved. + + DTD tags get thrown into XMLUnknowns. +*/ +class TINYXML2_LIB XMLUnknown : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLUnknown* ToUnknown() { + return this; + } + virtual const XMLUnknown* ToUnknown() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + XMLUnknown( XMLDocument* doc ); + virtual ~XMLUnknown(); + + char* ParseDeep( char*, StrPair* endTag ); + +private: + XMLUnknown( const XMLUnknown& ); // not supported + XMLUnknown& operator=( const XMLUnknown& ); // not supported +}; + + + +/** An attribute is a name-value pair. Elements have an arbitrary + number of attributes, each with a unique name. + + @note The attributes are not XMLNodes. You may only query the + Next() attribute in a list. +*/ +class TINYXML2_LIB XMLAttribute +{ + friend class XMLElement; +public: + /// The name of the attribute. + const char* Name() const; + + /// The value of the attribute. + const char* Value() const; + + /// The next attribute in the list. + const XMLAttribute* Next() const { + return _next; + } + + /** IntValue interprets the attribute as an integer, and returns the value. + If the value isn't an integer, 0 will be returned. There is no error checking; + use QueryIntValue() if you need error checking. + */ + int IntValue() const { + int i=0; + QueryIntValue( &i ); + return i; + } + /// Query as an unsigned integer. See IntValue() + unsigned UnsignedValue() const { + unsigned i=0; + QueryUnsignedValue( &i ); + return i; + } + /// Query as a boolean. See IntValue() + bool BoolValue() const { + bool b=false; + QueryBoolValue( &b ); + return b; + } + /// Query as a double. See IntValue() + double DoubleValue() const { + double d=0; + QueryDoubleValue( &d ); + return d; + } + /// Query as a float. See IntValue() + float FloatValue() const { + float f=0; + QueryFloatValue( &f ); + return f; + } + + /** QueryIntValue interprets the attribute as an integer, and returns the value + in the provided parameter. The function will return XML_NO_ERROR on success, + and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. + */ + XMLError QueryIntValue( int* value ) const; + /// See QueryIntValue + XMLError QueryUnsignedValue( unsigned int* value ) const; + /// See QueryIntValue + XMLError QueryBoolValue( bool* value ) const; + /// See QueryIntValue + XMLError QueryDoubleValue( double* value ) const; + /// See QueryIntValue + XMLError QueryFloatValue( float* value ) const; + + /// Set the attribute to a string value. + void SetAttribute( const char* value ); + /// Set the attribute to value. + void SetAttribute( int value ); + /// Set the attribute to value. + void SetAttribute( unsigned value ); + /// Set the attribute to value. + void SetAttribute( bool value ); + /// Set the attribute to value. + void SetAttribute( double value ); + /// Set the attribute to value. + void SetAttribute( float value ); + +private: + enum { BUF_SIZE = 200 }; + + XMLAttribute() : _next( 0 ), _memPool( 0 ) {} + virtual ~XMLAttribute() {} + + XMLAttribute( const XMLAttribute& ); // not supported + void operator=( const XMLAttribute& ); // not supported + void SetName( const char* name ); + + char* ParseDeep( char* p, bool processEntities ); + + mutable StrPair _name; + mutable StrPair _value; + XMLAttribute* _next; + MemPool* _memPool; +}; + + +/** The element is a container class. It has a value, the element name, + and can contain other elements, text, comments, and unknowns. + Elements also contain an arbitrary number of attributes. +*/ +class TINYXML2_LIB XMLElement : public XMLNode +{ + friend class XMLBase; + friend class XMLDocument; +public: + /// Get the name of an element (which is the Value() of the node.) + const char* Name() const { + return Value(); + } + /// Set the name of the element. + void SetName( const char* str, bool staticMem=false ) { + SetValue( str, staticMem ); + } + + virtual XMLElement* ToElement() { + return this; + } + virtual const XMLElement* ToElement() const { + return this; + } + virtual bool Accept( XMLVisitor* visitor ) const; + + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none + exists. For example: + + @verbatim + const char* value = ele->Attribute( "foo" ); + @endverbatim + + The 'value' parameter is normally null. However, if specified, + the attribute will only be returned if the 'name' and 'value' + match. This allow you to write code: + + @verbatim + if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); + @endverbatim + + rather than: + @verbatim + if ( ele->Attribute( "foo" ) ) { + if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); + } + @endverbatim + */ + const char* Attribute( const char* name, const char* value=0 ) const; + + /** Given an attribute name, IntAttribute() returns the value + of the attribute interpreted as an integer. 0 will be + returned if there is an error. For a method with error + checking, see QueryIntAttribute() + */ + int IntAttribute( const char* name ) const { + int i=0; + QueryIntAttribute( name, &i ); + return i; + } + /// See IntAttribute() + unsigned UnsignedAttribute( const char* name ) const { + unsigned i=0; + QueryUnsignedAttribute( name, &i ); + return i; + } + /// See IntAttribute() + bool BoolAttribute( const char* name ) const { + bool b=false; + QueryBoolAttribute( name, &b ); + return b; + } + /// See IntAttribute() + double DoubleAttribute( const char* name ) const { + double d=0; + QueryDoubleAttribute( name, &d ); + return d; + } + /// See IntAttribute() + float FloatAttribute( const char* name ) const { + float f=0; + QueryFloatAttribute( name, &f ); + return f; + } + + /** Given an attribute name, QueryIntAttribute() returns + XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion + can't be performed, or XML_NO_ATTRIBUTE if the attribute + doesn't exist. If successful, the result of the conversion + will be written to 'value'. If not successful, nothing will + be written to 'value'. This allows you to provide default + value: + + @verbatim + int value = 10; + QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 + @endverbatim + */ + XMLError QueryIntAttribute( const char* name, int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryIntValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryUnsignedValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryBoolAttribute( const char* name, bool* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryBoolValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryDoubleAttribute( const char* name, double* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryDoubleValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryFloatAttribute( const char* name, float* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryFloatValue( value ); + } + + + /** Given an attribute name, QueryAttribute() returns + XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion + can't be performed, or XML_NO_ATTRIBUTE if the attribute + doesn't exist. It is overloaded for the primitive types, + and is a generally more convenient replacement of + QueryIntAttribute() and related functions. + + If successful, the result of the conversion + will be written to 'value'. If not successful, nothing will + be written to 'value'. This allows you to provide default + value: + + @verbatim + int value = 10; + QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 + @endverbatim + */ + int QueryAttribute( const char* name, int* value ) const { + return QueryIntAttribute( name, value ); + } + + int QueryAttribute( const char* name, unsigned int* value ) const { + return QueryUnsignedAttribute( name, value ); + } + + int QueryAttribute( const char* name, bool* value ) const { + return QueryBoolAttribute( name, value ); + } + + int QueryAttribute( const char* name, double* value ) const { + return QueryDoubleAttribute( name, value ); + } + + int QueryAttribute( const char* name, float* value ) const { + return QueryFloatAttribute( name, value ); + } + + /// Sets the named attribute to value. + void SetAttribute( const char* name, const char* value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, int value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, unsigned value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, bool value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, double value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, float value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + + /** + Delete an attribute. + */ + void DeleteAttribute( const char* name ); + + /// Return the first attribute in the list. + const XMLAttribute* FirstAttribute() const { + return _rootAttribute; + } + /// Query a specific attribute in the list. + const XMLAttribute* FindAttribute( const char* name ) const; + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, GetText() is limited compared to getting the XMLText child + and accessing it directly. + + If the first child of 'this' is a XMLText, the GetText() + returns the character string of the Text node, else null is returned. + + This is a convenient method for getting the text of simple contained text: + @verbatim + This is text + const char* str = fooElement->GetText(); + @endverbatim + + 'str' will be a pointer to "This is text". + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim + + then the value of str would be null. The first child node isn't a text node, it is + another element. From this XML: + @verbatim + This is text + @endverbatim + GetText() will return "This is ". + */ + const char* GetText() const; + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, SetText() is limited compared to creating an XMLText child + and mutating it directly. + + If the first child of 'this' is a XMLText, SetText() sets its value to + the given string, otherwise it will create a first child that is an XMLText. + + This is a convenient method for setting the text of simple contained text: + @verbatim + This is text + fooElement->SetText( "Hullaballoo!" ); + Hullaballoo! + @endverbatim + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim + + then it will not change "This is text", but rather prefix it with a text element: + @verbatim + Hullaballoo!This is text + @endverbatim + + For this XML: + @verbatim + + @endverbatim + SetText() will generate + @verbatim + Hullaballoo! + @endverbatim + */ + void SetText( const char* inText ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( int value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( unsigned value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( bool value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( double value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( float value ); + + /** + Convenience method to query the value of a child text node. This is probably best + shown by example. Given you have a document is this form: + @verbatim + + 1 + 1.4 + + @endverbatim + + The QueryIntText() and similar functions provide a safe and easier way to get to the + "value" of x and y. + + @verbatim + int x = 0; + float y = 0; // types of x and y are contrived for example + const XMLElement* xElement = pointElement->FirstChildElement( "x" ); + const XMLElement* yElement = pointElement->FirstChildElement( "y" ); + xElement->QueryIntText( &x ); + yElement->QueryFloatText( &y ); + @endverbatim + + @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted + to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. + + */ + XMLError QueryIntText( int* ival ) const; + /// See QueryIntText() + XMLError QueryUnsignedText( unsigned* uval ) const; + /// See QueryIntText() + XMLError QueryBoolText( bool* bval ) const; + /// See QueryIntText() + XMLError QueryDoubleText( double* dval ) const; + /// See QueryIntText() + XMLError QueryFloatText( float* fval ) const; + + // internal: + enum { + OPEN, // + CLOSED, // + CLOSING // + }; + int ClosingType() const { + return _closingType; + } + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + char* ParseDeep( char* p, StrPair* endTag ); + +private: + XMLElement( XMLDocument* doc ); + virtual ~XMLElement(); + XMLElement( const XMLElement& ); // not supported + void operator=( const XMLElement& ); // not supported + + XMLAttribute* FindAttribute( const char* name ) { + return const_cast(const_cast(this)->FindAttribute( name )); + } + XMLAttribute* FindOrCreateAttribute( const char* name ); + //void LinkAttribute( XMLAttribute* attrib ); + char* ParseAttributes( char* p ); + static void DeleteAttribute( XMLAttribute* attribute ); + + enum { BUF_SIZE = 200 }; + int _closingType; + // The attribute list is ordered; there is no 'lastAttribute' + // because the list needs to be scanned for dupes before adding + // a new attribute. + XMLAttribute* _rootAttribute; +}; + + +enum Whitespace { + PRESERVE_WHITESPACE, + COLLAPSE_WHITESPACE +}; + + +/** A Document binds together all the functionality. + It can be saved, loaded, and printed to the screen. + All Nodes are connected and allocated to a Document. + If the Document is deleted, all its Nodes are also deleted. +*/ +class TINYXML2_LIB XMLDocument : public XMLNode +{ + friend class XMLElement; +public: + /// constructor + XMLDocument( bool processEntities = true, Whitespace = PRESERVE_WHITESPACE ); + ~XMLDocument(); + + virtual XMLDocument* ToDocument() { + TIXMLASSERT( this == _document ); + return this; + } + virtual const XMLDocument* ToDocument() const { + TIXMLASSERT( this == _document ); + return this; + } + + /** + Parse an XML file from a character string. + Returns XML_NO_ERROR (0) on success, or + an errorID. + + You may optionally pass in the 'nBytes', which is + the number of bytes which will be parsed. If not + specified, TinyXML-2 will assume 'xml' points to a + null terminated string. + */ + XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); + + /** + Load an XML file from disk. + Returns XML_NO_ERROR (0) on success, or + an errorID. + */ + XMLError LoadFile( const char* filename ); + + /** + Load an XML file from disk. You are responsible + for providing and closing the FILE*. + + NOTE: The file should be opened as binary ("rb") + not text in order for TinyXML-2 to correctly + do newline normalization. + + Returns XML_NO_ERROR (0) on success, or + an errorID. + */ + XMLError LoadFile( FILE* ); + + /** + Save the XML file to disk. + Returns XML_NO_ERROR (0) on success, or + an errorID. + */ + XMLError SaveFile( const char* filename, bool compact = false ); + + /** + Save the XML file to disk. You are responsible + for providing and closing the FILE*. + + Returns XML_NO_ERROR (0) on success, or + an errorID. + */ + XMLError SaveFile( FILE* fp, bool compact = false ); + + bool ProcessEntities() const { + return _processEntities; + } + Whitespace WhitespaceMode() const { + return _whitespace; + } + + /** + Returns true if this document has a leading Byte Order Mark of UTF8. + */ + bool HasBOM() const { + return _writeBOM; + } + /** Sets whether to write the BOM when writing the file. + */ + void SetBOM( bool useBOM ) { + _writeBOM = useBOM; + } + + /** Return the root element of DOM. Equivalent to FirstChildElement(). + To get the first node, use FirstChild(). + */ + XMLElement* RootElement() { + return FirstChildElement(); + } + const XMLElement* RootElement() const { + return FirstChildElement(); + } + + /** Print the Document. If the Printer is not provided, it will + print to stdout. If you provide Printer, this can print to a file: + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Or you can use a printer to print to memory: + @verbatim + XMLPrinter printer; + doc.Print( &printer ); + // printer.CStr() has a const char* to the XML + @endverbatim + */ + void Print( XMLPrinter* streamer=0 ) const; + virtual bool Accept( XMLVisitor* visitor ) const; + + /** + Create a new Element associated with + this Document. The memory for the Element + is managed by the Document. + */ + XMLElement* NewElement( const char* name ); + /** + Create a new Comment associated with + this Document. The memory for the Comment + is managed by the Document. + */ + XMLComment* NewComment( const char* comment ); + /** + Create a new Text associated with + this Document. The memory for the Text + is managed by the Document. + */ + XMLText* NewText( const char* text ); + /** + Create a new Declaration associated with + this Document. The memory for the object + is managed by the Document. + + If the 'text' param is null, the standard + declaration is used.: + @verbatim + + @endverbatim + */ + XMLDeclaration* NewDeclaration( const char* text=0 ); + /** + Create a new Unknown associated with + this Document. The memory for the object + is managed by the Document. + */ + XMLUnknown* NewUnknown( const char* text ); + + /** + Delete a node associated with this document. + It will be unlinked from the DOM. + */ + void DeleteNode( XMLNode* node ); + + void SetError( XMLError error, const char* str1, const char* str2 ); + + /// Return true if there was an error parsing the document. + bool Error() const { + return _errorID != XML_NO_ERROR; + } + /// Return the errorID. + XMLError ErrorID() const { + return _errorID; + } + const char* ErrorName() const; + + /// Return a possibly helpful diagnostic location or string. + const char* GetErrorStr1() const { + return _errorStr1; + } + /// Return a possibly helpful secondary diagnostic location or string. + const char* GetErrorStr2() const { + return _errorStr2; + } + /// If there is an error, print it to stdout. + void PrintError() const; + + /// Clear the document, resetting it to the initial state. + void Clear(); + + // internal + char* Identify( char* p, XMLNode** node ); + + virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { + return 0; + } + virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { + return false; + } + +private: + XMLDocument( const XMLDocument& ); // not supported + void operator=( const XMLDocument& ); // not supported + + bool _writeBOM; + bool _processEntities; + XMLError _errorID; + Whitespace _whitespace; + const char* _errorStr1; + const char* _errorStr2; + char* _charBuffer; + + MemPoolT< sizeof(XMLElement) > _elementPool; + MemPoolT< sizeof(XMLAttribute) > _attributePool; + MemPoolT< sizeof(XMLText) > _textPool; + MemPoolT< sizeof(XMLComment) > _commentPool; + + static const char* _errorNames[XML_ERROR_COUNT]; + + void Parse(); +}; + + +/** + A XMLHandle is a class that wraps a node pointer with null checks; this is + an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 + DOM structure. It is a separate utility class. + + Take an example: + @verbatim + + + + + + + @endverbatim + + Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very + easy to write a *lot* of code that looks like: + + @verbatim + XMLElement* root = document.FirstChildElement( "Document" ); + if ( root ) + { + XMLElement* element = root->FirstChildElement( "Element" ); + if ( element ) + { + XMLElement* child = element->FirstChildElement( "Child" ); + if ( child ) + { + XMLElement* child2 = child->NextSiblingElement( "Child" ); + if ( child2 ) + { + // Finally do something useful. + @endverbatim + + And that doesn't even cover "else" cases. XMLHandle addresses the verbosity + of such code. A XMLHandle checks for null pointers so it is perfectly safe + and correct to use: + + @verbatim + XMLHandle docHandle( &document ); + XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); + if ( child2 ) + { + // do something useful + @endverbatim + + Which is MUCH more concise and useful. + + It is also safe to copy handles - internally they are nothing more than node pointers. + @verbatim + XMLHandle handleCopy = handle; + @endverbatim + + See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. +*/ +class TINYXML2_LIB XMLHandle +{ +public: + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + XMLHandle( XMLNode* node ) { + _node = node; + } + /// Create a handle from a node. + XMLHandle( XMLNode& node ) { + _node = &node; + } + /// Copy constructor + XMLHandle( const XMLHandle& ref ) { + _node = ref._node; + } + /// Assignment + XMLHandle& operator=( const XMLHandle& ref ) { + _node = ref._node; + return *this; + } + + /// Get the first child of this handle. + XMLHandle FirstChild() { + return XMLHandle( _node ? _node->FirstChild() : 0 ); + } + /// Get the first child element of this handle. + XMLHandle FirstChildElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); + } + /// Get the last child of this handle. + XMLHandle LastChild() { + return XMLHandle( _node ? _node->LastChild() : 0 ); + } + /// Get the last child element of this handle. + XMLHandle LastChildElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); + } + /// Get the previous sibling of this handle. + XMLHandle PreviousSibling() { + return XMLHandle( _node ? _node->PreviousSibling() : 0 ); + } + /// Get the previous sibling element of this handle. + XMLHandle PreviousSiblingElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); + } + /// Get the next sibling of this handle. + XMLHandle NextSibling() { + return XMLHandle( _node ? _node->NextSibling() : 0 ); + } + /// Get the next sibling element of this handle. + XMLHandle NextSiblingElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); + } + + /// Safe cast to XMLNode. This can return null. + XMLNode* ToNode() { + return _node; + } + /// Safe cast to XMLElement. This can return null. + XMLElement* ToElement() { + return ( ( _node == 0 ) ? 0 : _node->ToElement() ); + } + /// Safe cast to XMLText. This can return null. + XMLText* ToText() { + return ( ( _node == 0 ) ? 0 : _node->ToText() ); + } + /// Safe cast to XMLUnknown. This can return null. + XMLUnknown* ToUnknown() { + return ( ( _node == 0 ) ? 0 : _node->ToUnknown() ); + } + /// Safe cast to XMLDeclaration. This can return null. + XMLDeclaration* ToDeclaration() { + return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() ); + } + +private: + XMLNode* _node; +}; + + +/** + A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the + same in all regards, except for the 'const' qualifiers. See XMLHandle for API. +*/ +class TINYXML2_LIB XMLConstHandle +{ +public: + XMLConstHandle( const XMLNode* node ) { + _node = node; + } + XMLConstHandle( const XMLNode& node ) { + _node = &node; + } + XMLConstHandle( const XMLConstHandle& ref ) { + _node = ref._node; + } + + XMLConstHandle& operator=( const XMLConstHandle& ref ) { + _node = ref._node; + return *this; + } + + const XMLConstHandle FirstChild() const { + return XMLConstHandle( _node ? _node->FirstChild() : 0 ); + } + const XMLConstHandle FirstChildElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); + } + const XMLConstHandle LastChild() const { + return XMLConstHandle( _node ? _node->LastChild() : 0 ); + } + const XMLConstHandle LastChildElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); + } + const XMLConstHandle PreviousSibling() const { + return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); + } + const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); + } + const XMLConstHandle NextSibling() const { + return XMLConstHandle( _node ? _node->NextSibling() : 0 ); + } + const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); + } + + + const XMLNode* ToNode() const { + return _node; + } + const XMLElement* ToElement() const { + return ( ( _node == 0 ) ? 0 : _node->ToElement() ); + } + const XMLText* ToText() const { + return ( ( _node == 0 ) ? 0 : _node->ToText() ); + } + const XMLUnknown* ToUnknown() const { + return ( ( _node == 0 ) ? 0 : _node->ToUnknown() ); + } + const XMLDeclaration* ToDeclaration() const { + return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() ); + } + +private: + const XMLNode* _node; +}; + + +/** + Printing functionality. The XMLPrinter gives you more + options than the XMLDocument::Print() method. + + It can: + -# Print to memory. + -# Print to a file you provide. + -# Print XML without a XMLDocument. + + Print to Memory + + @verbatim + XMLPrinter printer; + doc.Print( &printer ); + SomeFunction( printer.CStr() ); + @endverbatim + + Print to a File + + You provide the file pointer. + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Print without a XMLDocument + + When loading, an XML parser is very useful. However, sometimes + when saving, it just gets in the way. The code is often set up + for streaming, and constructing the DOM is just overhead. + + The Printer supports the streaming case. The following code + prints out a trivially simple XML file without ever creating + an XML document. + + @verbatim + XMLPrinter printer( fp ); + printer.OpenElement( "foo" ); + printer.PushAttribute( "foo", "bar" ); + printer.CloseElement(); + @endverbatim +*/ +class TINYXML2_LIB XMLPrinter : public XMLVisitor +{ +public: + /** Construct the printer. If the FILE* is specified, + this will print to the FILE. Else it will print + to memory, and the result is available in CStr(). + If 'compact' is set to true, then output is created + with only required whitespace and newlines. + */ + XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); + virtual ~XMLPrinter() {} + + /** If streaming, write the BOM and declaration. */ + void PushHeader( bool writeBOM, bool writeDeclaration ); + /** If streaming, start writing an element. + The element must be closed with CloseElement() + */ + void OpenElement( const char* name, bool compactMode=false ); + /// If streaming, add an attribute to an open element. + void PushAttribute( const char* name, const char* value ); + void PushAttribute( const char* name, int value ); + void PushAttribute( const char* name, unsigned value ); + void PushAttribute( const char* name, bool value ); + void PushAttribute( const char* name, double value ); + /// If streaming, close the Element. + virtual void CloseElement( bool compactMode=false ); + + /// Add a text node. + void PushText( const char* text, bool cdata=false ); + /// Add a text node from an integer. + void PushText( int value ); + /// Add a text node from an unsigned. + void PushText( unsigned value ); + /// Add a text node from a bool. + void PushText( bool value ); + /// Add a text node from a float. + void PushText( float value ); + /// Add a text node from a double. + void PushText( double value ); + + /// Add a comment + void PushComment( const char* comment ); + + void PushDeclaration( const char* value ); + void PushUnknown( const char* value ); + + virtual bool VisitEnter( const XMLDocument& /*doc*/ ); + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); + virtual bool VisitExit( const XMLElement& element ); + + virtual bool Visit( const XMLText& text ); + virtual bool Visit( const XMLComment& comment ); + virtual bool Visit( const XMLDeclaration& declaration ); + virtual bool Visit( const XMLUnknown& unknown ); + + /** + If in print to memory mode, return a pointer to + the XML file in memory. + */ + const char* CStr() const { + return _buffer.Mem(); + } + /** + If in print to memory mode, return the size + of the XML file in memory. (Note the size returned + includes the terminating null.) + */ + int CStrSize() const { + return _buffer.Size(); + } + /** + If in print to memory mode, reset the buffer to the + beginning. + */ + void ClearBuffer() { + _buffer.Clear(); + _buffer.Push(0); + } + +protected: + virtual bool CompactMode( const XMLElement& ) { return _compactMode; } + + /** Prints out the space before an element. You may override to change + the space and tabs used. A PrintSpace() override should call Print(). + */ + virtual void PrintSpace( int depth ); + void Print( const char* format, ... ); + + void SealElementIfJustOpened(); + bool _elementJustOpened; + DynArray< const char*, 10 > _stack; + +private: + void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. + + bool _firstElement; + FILE* _fp; + int _depth; + int _textDepth; + bool _processEntities; + bool _compactMode; + + enum { + ENTITY_RANGE = 64, + BUF_SIZE = 200 + }; + bool _entityFlag[ENTITY_RANGE]; + bool _restrictedEntityFlag[ENTITY_RANGE]; + + DynArray< char, 20 > _buffer; +}; + + +} // tinyxml2 + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // TINYXML2_INCLUDED diff --git a/main.cpp b/main.cpp index f5e02fa..feb95e1 100644 --- a/main.cpp +++ b/main.cpp @@ -1,75 +1,31 @@ #include -#include -#include +//#include +//#include #include -#include -#include -#include -#include -#include - -#include -#include - -#include "sensors/SensorFactory.h" #include "Controller.h" -#include "ui/map/MapView.h" +#include "ui/map/3D/MapView3D.h" -#include - -#include -#include -#include -#include -#include - - - - -struct MyNode : public GridPoint, public GridNode, public WiFiGridNode<10> { - - float navImportance; - MyNode() {;} - MyNode(const float x_cm, const float y_cm, const float z_cm) : GridPoint(x_cm, y_cm, z_cm) {;} - -public: - - static void staticSerialize(std::ostream& out) { - WiFiGridNode::staticSerialize(out); - } - - static void staticDeserialize(std::istream& inp) { - WiFiGridNode::staticDeserialize(inp); - } - -}; +#include "tests/RuntimeTests.h" int main(int argc, char *argv[]) { + + RuntimeTests::run(); + QApplication app(argc, argv); + std::cout << "resampling mit streuung? z.B in nachbar nodes?"; + std::cout << "gerade am anfang geht seeehr viel verloren"; + Controller ctrl; Point3 eye(40,42,1.8); - ctrl.getMapView()->setLookEye(eye); - ctrl.getMapView()->setLookDir(Point3(-1, 0, -0.1)); - - -// auto run = [&] () { -// static float r = 0; -// while(true) { -// r += 0.01; -// eye += Point3(-0.01, 0, 0); -// ctrl.getMapView()->setLookEye(eye); -// usleep(1000*50); -// } -// }; - -// std::thread t(run); + ctrl.getMapView3D()->setLookEye(eye); + ctrl.getMapView3D()->setLookDir(Point3(-1, 0, -0.1)); return app.exec(); diff --git a/nav/Filter.h b/nav/Filter.h index 9e3ee35..47384c1 100644 --- a/nav/Filter.h +++ b/nav/Filter.h @@ -12,18 +12,21 @@ #include #include #include +#include #include #include #include -#include +#include #include #include "State.h" #include "Node.h" - +#include "NodeResampling.h" #include "../Settings.h" +#include + class PFInit : public K::ParticleFilterInitializer { private: @@ -42,17 +45,20 @@ public: std::uniform_int_distribution distIdx(0, grid->getNumNodes()-1); std::uniform_real_distribution distHead(0, 2*M_PI); + for (K::Particle& p : particles) { const int idx = distIdx(gen); const MyGridNode& node = (*grid)[idx]; p.state.position = node; // random position p.state.heading.direction = Heading(distHead(gen)); // random heading + p.weight = 1.0 / particles.size(); // equal weight } // // fix position + heading // for (K::Particle& p : particles) { -// const int idx = 9000; -// const MyGridNode& node = (*grid)[idx]; +//// const int idx = 9000; +//// const MyGridNode& node = (*grid)[idx]; +// const MyGridNode& node = grid->getNodeFor(GridPoint(2000, 2000, 0)); // center of the testmap // p.state.position = node; // p.state.heading.direction = Heading(0); // } @@ -65,28 +71,34 @@ class PFTrans : public K::ParticleFilterTransition { public: + /** local, static control-data COPY */ + MyControl ctrl; + Grid* grid; GridWalker walker; WalkModuleFavorZ modFavorZ; WalkModuleHeadingControl modHeading; WalkModuleNodeImportance modImportance; - WalkModuleButterActivity modBarometer; WalkModuleFollowDestination modDestination; + WalkModuleActivityControl modActivity; + + NodeResampling resampler; std::minstd_rand gen; public: - PFTrans(Grid* grid, MyControl* ctrl) : grid(grid), modHeading(ctrl, Settings::turnSigma), modDestination(*grid) { + PFTrans(Grid* grid) : grid(grid), modHeading(&ctrl, Settings::IMU::turnSigma), modDestination(*grid), modActivity(&ctrl), resampler(*grid) { - walker.addModule(&modFavorZ); + //walker.addModule(&modFavorZ); walker.addModule(&modHeading); - walker.addModule(&modImportance); - walker.addModule(&modBarometer); - walker.addModule(&modDestination); + //walker.addModule(&modImportance); + walker.addModule(&modActivity); + if (Settings::destination != GridPoint(0,0,0)) { + //walker.addModule(&modDestination); modDestination.setDestination(grid->getNodeFor(Settings::destination)); } @@ -94,16 +106,52 @@ public: - void transition(std::vector>& particles, const MyControl* control) override { + void transition(std::vector>& particles, const MyControl* _ctrl) override { - std::normal_distribution noise(0, Settings::stepSigma); + // local copy!! observation might be changed async outside!! (will really produces crashes!) + this->ctrl = *_ctrl; + ((MyControl*)_ctrl)->resetAfterTransition(); - for (K::Particle& p : particles) { - const float dist_m = std::abs(control->numStepsSinceLastTransition * Settings::stepLength + noise(gen)); - p.state = walker.getDestination(*grid, p.state, dist_m); + std::normal_distribution noise(0, Settings::IMU::stepSigma); + double probSum = 0; + + + + + // seems OK +// float sum = 0; +// for (int i = 0; i < 1000; ++i) { +// float val = noise(gen); +// sum += std::abs(val); +// } + //Log::add("123", "sum: " + std::to_string(sum)); + //Log::add("123", std::to_string(Timestamp::fromRunningTime().ms()) + ": " + std::to_string(ctrl.numStepsSinceLastTransition)); + + //for (K::Particle& p : particles) { + #pragma omp parallel for num_threads(2) + for (int i = 0; i < (int) particles.size(); ++i) { + K::Particle& p = particles[i]; + const float dist_m = std::abs(ctrl.numStepsSinceLastTransition * Settings::IMU::stepLength + noise(gen)); + double prob; + p.state = walker.getDestination(*grid, p.state, dist_m, prob); + //p.weight *= prob;//(prob > 0.01) ? (1.0) : (0.15); + //p.weight = (prob > 0.01) ? (1.0) : (0.15); + //p.weight = prob; + p.weight = 1.0; // reset + p.weight = std::pow(p.weight, 0.1); // make all particles a little more equal [less strict] + p.weight *= std::pow(prob, 0.1); // add grid-walk-probability + if (p.weight != p.weight) {throw Exception("nan");} + probSum += prob; + //p.weight = Distribution::Exponential::getProbability(5.0, prob); } - ((MyControl*)control)->resetAfterTransition(); +// const double avgProb = probSum / particles.size(); +// const double threshold = avgProb * 0.15; +// for (int i = 0; i < (int) particles.size(); ++i) { +// K::Particle& p = particles[i]; +// p.weight = (p.weight > threshold) ? (1.0) : (0.01); // downvote all transitions below the threshold +// //p.weight = 1; +// } } @@ -111,12 +159,51 @@ public: class PFEval : public K::ParticleFilterEvaluation { + Grid* grid; + WiFiModelLogDistCeiling& wifiModel; - WiFiObserverFree wiFiProbability; + + + //WiFiObserverFree wiFiProbability; // free-calculation + WiFiObserverGrid wiFiProbability; // grid-calculation + + // how to perform VAP grouping. also see calibration in Controller.cpp + VAPGrouper vg = VAPGrouper(VAPGrouper::Mode::LAST_MAC_DIGIT_TO_ZERO, VAPGrouper::Aggregation::AVERAGE); + + // smartphone is 1.3 meter above ground + const Point3 person = Point3(0,0,Settings::smartphoneAboveGround); public: - PFEval(WiFiModelLogDistCeiling& wifiModel) : wifiModel(wifiModel), wiFiProbability(Settings::wifiSigma, wifiModel) { + PFEval(Grid* grid, WiFiModelLogDistCeiling& wifiModel) : + grid(grid), wifiModel(wifiModel), + //wiFiProbability(Settings::WiFiModel::sigma, wifiModel) { // WiFi free + wiFiProbability(Settings::WiFiModel::sigma) { // WiFi grid + + + } + + double getStairProb(const K::Particle& p, const ActivityButterPressure::Activity act) { + + const float kappa = 0.75; + + const MyGridNode& gn = grid->getNodeFor(p.state.position); + switch (act) { + + case ActivityButterPressure::Activity::STAY: + if (gn.getType() == GridNode::TYPE_FLOOR) {return kappa;} + if (gn.getType() == GridNode::TYPE_DOOR) {return kappa;} + {return 1-kappa;} + + case ActivityButterPressure::Activity::UP: + case ActivityButterPressure::Activity::DOWN: + if (gn.getType() == GridNode::TYPE_STAIR) {return kappa;} + if (gn.getType() == GridNode::TYPE_ELEVATOR) {return kappa;} + {return 1-kappa;} + + } + + return 1.0; } @@ -124,18 +211,31 @@ public: double sum = 0; - // smartphone is 1.3 meter above ground - const Point3 person(0,0,Settings::smartphoneAboveGround); - // local copy!! observation might be changed async outside!! (will really produces crashes!) const MyObservation observation = _observation; + // vap-grouping + const WiFiMeasurements wifiObs = vg.group(_observation.wifi); + for (K::Particle& p : particles) { - const double pWiFi = wiFiProbability.getProbability(p.state.position.inMeter()+person, observation.currentTime, observation.wifi); + + + // WiFi free + //const double pWiFi = wiFiProbability.getProbability(p.state.position.inMeter()+person, observation.currentTime, vg.group(observation.wifi)); + + // WiFi grid + const MyGridNode& node = grid->getNodeFor(p.state.position); + const double pWiFi = wiFiProbability.getProbability(node, observation.currentTime, wifiObs); + + const double pStair = getStairProb(p, observation.activity); const double pGPS = 1; - const double prob = pWiFi * pGPS; - p.weight = prob; - sum += prob; + const double prob = pWiFi * pGPS * pStair; + p.weight *= prob; // NOTE: keeps the weight returned by the transition step! + //p.weight = prob; // does NOT keep the weights returned by the transition step + sum += p.weight; + + if (p.weight != p.weight) {throw Exception("nan");} + } return sum; diff --git a/nav/NavController.h b/nav/NavController.h index e6d963d..741552d 100644 --- a/nav/NavController.h +++ b/nav/NavController.h @@ -10,7 +10,8 @@ #include "../sensors/TurnSensor.h" #include "../ui/debug/SensorDataWidget.h" -#include "../ui/map/MapView.h" +#include "../ui/map/3D/MapView3D.h" +#include "../ui/debug/InfoWidget.h" #include #include @@ -18,24 +19,25 @@ #include "State.h" #include "Filter.h" #include "Controller.h" +#include "NavControllerListener.h" #include #include #include #include +#ifndef ANDROID +#include +#endif + #include "Settings.h" #include "RegionalResampling.h" +#include "NodeResampling.h" Q_DECLARE_METATYPE(const void*) - - - - - class NavController : public SensorListener, public SensorListener, @@ -43,7 +45,9 @@ class NavController : public SensorListener, public SensorListener, public SensorListener, - public SensorListener { + public SensorListener, + public SensorListener { + private: @@ -56,106 +60,164 @@ private: MyControl curCtrl; bool running = false; - std::thread tUpdate; + std::thread tFilter; std::thread tDisplay; std::unique_ptr> pf; + /** the estimated path */ + std::vector estPath; + + /** all listeners */ + std::vector listeners; + public: virtual ~NavController() { if (running) {stop();} } + /** ctor */ NavController(Controller* mainController, Grid* grid, Floorplan::IndoorMap* im) : mainController(mainController), grid(grid), wifiModel(im), im(im) { - wifiModel.loadAPs(im, Settings::wifiTXP, Settings::wifiEXP, Settings::wifiWAF); - - SensorFactory::get().getAccelerometer().addListener(this); - SensorFactory::get().getGyroscope().addListener(this); - SensorFactory::get().getBarometer().addListener(this); - SensorFactory::get().getWiFi().addListener(this); - SensorFactory::get().getSteps().addListener(this); - SensorFactory::get().getTurns().addListener(this); - + // filter init std::unique_ptr> init(new PFInit(grid)); + // estimation //std::unique_ptr> estimation(new K::ParticleFilterEstimationWeightedAverage()); - std::unique_ptr> estimation(new K::ParticleFilterEstimationOrderedWeightedAverage(0.1)); + std::unique_ptr> estimation(new K::ParticleFilterEstimationOrderedWeightedAverage(0.5)); + // resampling + std::unique_ptr> resample(new NodeResampling(*grid)); //std::unique_ptr> resample(new K::ParticleFilterResamplingSimple()); - //std::unique_ptr> resample(new K::ParticleFilterResamplingPercent(0.10)); - std::unique_ptr resample(new RegionalResampling()); + //std::unique_ptr> resample(new K::ParticleFilterResamplingPercent(0.05)); + //std::unique_ptr resample(new RegionalResampling()); + // eval and transition + wifiModel.loadAPs(im, Settings::WiFiModel::TXP, Settings::WiFiModel::EXP, Settings::WiFiModel::WAF); + std::unique_ptr> eval(new PFEval(grid, wifiModel)); + std::unique_ptr> transition(new PFTrans(grid)); - std::unique_ptr> eval(new PFEval(wifiModel)); - std::unique_ptr> transition(new PFTrans(grid, &curCtrl)); - + // setup the filter pf = std::unique_ptr>(new K::ParticleFilter(Settings::numParticles, std::move(init))); pf->setTransition(std::move(transition)); pf->setEvaluation(std::move(eval)); pf->setEstimation(std::move(estimation)); pf->setResampling(std::move(resample)); - pf->setNEffThreshold(1.0); + pf->setNEffThreshold(0.75); + //pf->setNEffThreshold(0.65); // still too low? + //pf->setNEffThreshold(0.25); // too low + + // attach as listener to all sensors + SensorFactory::get().getAccelerometer().addListener(this); + SensorFactory::get().getGyroscope().addListener(this); + SensorFactory::get().getBarometer().addListener(this); + SensorFactory::get().getWiFi().addListener(this); + SensorFactory::get().getSteps().addListener(this); + SensorFactory::get().getTurns().addListener(this); + SensorFactory::get().getActivity().addListener(this); + + // hacky.. but we need to call this one from the main thread! + //mainController->getMapView()->showParticles(pf->getParticles()); + qRegisterMetaType(); } + /** attach a new event listener */ + void addListener(NavControllerListener* l) { + listeners.push_back(l); + } + void start() { + Assert::isFalse(running, "already started!"); running = true; - tUpdate = std::thread(&NavController::update, this); - tDisplay = std::thread(&NavController::display, this); + curCtrl.resetAfterTransition(); // ensure we start empty ;) + tFilter = std::thread(&NavController::filterUpdateLoop, this); + tDisplay = std::thread(&NavController::updateMapViewLoop, this); + + // start all sensors + SensorFactory::get().getAccelerometer().start(); + SensorFactory::get().getGyroscope().start(); + SensorFactory::get().getBarometer().start(); + SensorFactory::get().getWiFi().start(); + +#ifndef ANDROID + // #include + // run with + // valgrind --tool=callgrind --quiet --instr-atstart=no ./yasmin + // show with + // kcachegrind callgrind.out.xxxx + CALLGRIND_START_INSTRUMENTATION; +#endif + } void stop() { Assert::isTrue(running, "not started!"); running = false; - tUpdate.join(); + tFilter.join(); tDisplay.join(); } + void onSensorData(Sensor* sensor, const Timestamp ts, const AccelerometerData& data) override { (void) sensor; - curObs.currentTime = ts; + (void) data; + (void) ts; + gotSensorData(ts); } void onSensorData(Sensor* sensor, const Timestamp ts, const GyroscopeData& data) override { (void) sensor; - curObs.currentTime = ts; + (void) ts; + (void) data; + gotSensorData(ts); } void onSensorData(Sensor* sensor, const Timestamp ts, const BarometerData& data) override { (void) sensor; - curObs.currentTime = ts; + (void) ts; + (void) data; + gotSensorData(ts); } void onSensorData(Sensor* sensor, const Timestamp ts, const WiFiMeasurements& data) override { (void) sensor; (void) ts; - curObs.currentTime = ts; curObs.wifi = data; + gotSensorData(ts); } void onSensorData(Sensor* sensor, const Timestamp ts, const GPSData& data) override { (void) sensor; (void) ts; - curObs.currentTime = ts; curObs.gps = data; + gotSensorData(ts); } void onSensorData(Sensor* sensor, const Timestamp ts, const StepData& data) override { (void) sensor; (void) ts; - curObs.currentTime = ts; curCtrl.numStepsSinceLastTransition += data.stepsSinceLastEvent; // set to zero after each transition + gotSensorData(ts); } void onSensorData(Sensor* sensor, const Timestamp ts, const TurnData& data) override { (void) sensor; (void) ts; - curObs.currentTime = ts; curCtrl.turnSinceLastTransition_rad += data.radSinceLastEvent; // set to zero after each transition + gotSensorData(ts); + } + + void onSensorData(Sensor* sensor, const Timestamp ts, const ActivityData& data) override { + (void) sensor; + (void) ts; + curCtrl.activity = data.curActivity; + curObs.activity = data.curActivity; + debugActivity(data.curActivity); + gotSensorData(ts); } int cameraMode = 0; @@ -165,12 +227,29 @@ public: private: + /** called when any sensor has received new data */ + void gotSensorData(const Timestamp ts) { + curObs.currentTime = ts; + if (Settings::Filter::useMainThread) {filterUpdateIfNeeded();} + } + + + void debugActivity(const ActivityData& activity) { + QString act; + switch(activity.curActivity) { + case ActivityButterPressure::Activity::STAY: act = "STAY"; break; + case ActivityButterPressure::Activity::DOWN: act = "DOWN"; break; + case ActivityButterPressure::Activity::UP: act = "UP"; break; + default: act = "???"; break; + } + Assert::isTrue(QMetaObject::invokeMethod(mainController->getInfoWidget(), "showActivity", Qt::QueuedConnection, Q_ARG(const QString&, act)), "call failed"); + } + /** particle-filter update loop */ - void update() { + void filterUpdateLoop() { - Timestamp lastTransition; - while(running) { + while(running && !Settings::Filter::useMainThread) { // // fixed update rate based on the systems time -> LIVE! even for offline data // const Timestamp ts1 = Timestamp::fromUnixTime(); @@ -180,82 +259,94 @@ private: // const Timestamp sleep = Timestamp::fromMS(500) - needed; // std::this_thread::sleep_for(std::chrono::milliseconds(sleep.ms())); - // fixed update rate based on incoming sensor data - // allows working with live data and faster for offline data - const Timestamp diff = curObs.currentTime - lastTransition; - if (diff > Timestamp::fromMS(500)) { - doUpdate(); - lastTransition = curObs.currentTime; - } else { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - } + const bool wasUpdated = filterUpdateIfNeeded(); + if (!wasUpdated) { std::this_thread::sleep_for(std::chrono::milliseconds(2)); } } } + Timestamp lastTransition; + + /** check whether its time for a filter update, and if so, execute the update and return true */ + bool filterUpdateIfNeeded() { + + //static float avgSum = 0; + //static int avgCount = 0; + + // fixed update rate based on incoming sensor data + // allows working with live data and faster for offline data + const Timestamp diff = curObs.currentTime - lastTransition; + if (diff >= Settings::Filter::updateEvery) { + + // as the difference is slightly above the 500ms, calculate the error and incorporate it into the next one + const Timestamp err = diff - Settings::Filter::updateEvery; + lastTransition = curObs.currentTime - err; + + const Timestamp ts1 = Timestamp::fromUnixTime(); + filterUpdate(); + const Timestamp ts2 = Timestamp::fromUnixTime(); + const Timestamp tsDiff = ts2-ts1; + const QString filterTime = QString::number(tsDiff.ms()); + //avgSum += tsDiff.ms(); ++avgCount; std::cout << "ts:" << curObs.currentTime << " avg:" << (avgSum/avgCount) << std::endl; + QMetaObject::invokeMethod(mainController->getInfoWidget(), "showFilterTime", Qt::QueuedConnection, Q_ARG(const QString&, filterTime)); + return true; + + } else { + + return false; + + } + + } + MyState curEst; - //MyState lastEst; + DijkstraPath pathToDest; - void doUpdate() { + /** perform a filter-update (called from a background-loop) */ + void filterUpdate() { //lastEst = curEst; curEst = pf->update(&curCtrl, curObs); + Log::add("Nav", "cur est: " + curEst.position.asString()); - // hacky.. but we need to call this one from the main thread! - //mainController->getMapView()->showParticles(pf->getParticles()); - qRegisterMetaType(); - Assert::isTrue(QMetaObject::invokeMethod(mainController->getMapView(), "showParticles", Qt::QueuedConnection, Q_ARG(const void*, &pf->getParticles())), "call failed"); + // inform listeners about the new estimation + for (NavControllerListener* l : listeners) {l->onNewEstimation(curEst.position.inMeter());} + Assert::isTrue(QMetaObject::invokeMethod(mainController->getMapView3D(), "showParticles", Qt::QueuedConnection, Q_ARG(const void*, &pf->getParticles())), "call failed"); + Assert::isTrue(QMetaObject::invokeMethod(mainController->getMapView2D(), "showParticles", Qt::QueuedConnection, Q_ARG(const void*, &pf->getParticles())), "call failed"); + + // update estimated path + estPath.push_back(curEst.position.inMeter()); + Assert::isTrue(QMetaObject::invokeMethod(mainController->getMapView3D(), "setPathWalked", Qt::QueuedConnection, Q_ARG(const void*, &estPath)), "call failed"); + Assert::isTrue(QMetaObject::invokeMethod(mainController->getMapView2D(), "setPathWalked", Qt::QueuedConnection, Q_ARG(const void*, &estPath)), "call failed"); PFTrans* trans = (PFTrans*)pf->getTransition(); const MyGridNode* node = grid->getNodePtrFor(curEst.position); if (node) { - const DijkstraPath path = trans->modDestination.getShortestPath(*node); + try { + pathToDest = trans->modDestination.getShortestPath(*node); + Assert::isTrue(QMetaObject::invokeMethod(mainController->getMapView3D(), "setPathToDestination", Qt::QueuedConnection, Q_ARG(const void*, &pathToDest)), "call failed"); + Assert::isTrue(QMetaObject::invokeMethod(mainController->getMapView2D(), "setPathToDestination", Qt::QueuedConnection, Q_ARG(const void*, &pathToDest)), "call failed"); + } catch (...) {;} + } // mainController->getMapView()->showGridImportance(); - Assert::isTrue(QMetaObject::invokeMethod(mainController->getMapView(), "setPath", Qt::QueuedConnection, Q_ARG(const void*, &path)), "call failed"); - } - - /* - static K::Gnuplot gp; - K::GnuplotSplot plot; - K::GnuplotSplotElementLines lines; plot.add(&lines); - K::GnuplotSplotElementPoints points; plot.add(&points); - K::GnuplotSplotElementPoints best; plot.add(&best); best.setPointSize(2); best.setColorHex("#0000ff"); - - for (const K::Particle& p : pf->getParticles()) { - const Point3 pos = p.state.position.inMeter(); - points.add(K::GnuplotPoint3(pos.x, pos.y, pos.z)); - } - - for (const Floorplan::Floor* f : im->floors) { - for (const Floorplan::FloorOutlinePolygon* polygon : f->outline) { - for (int i = 0; i < polygon->poly.points.size(); ++i) { - const Point2 p1 = polygon->poly.points[i]; - const Point2 p2 = polygon->poly.points[(i+1)%polygon->poly.points.size()]; - K::GnuplotPoint3 gp1(p1.x, p1.y, f->atHeight); - K::GnuplotPoint3 gp2(p2.x, p2.y, f->atHeight); - lines.addSegment(gp1, gp2); - } - } - } - - K::GnuplotPoint3 gpBest(curEst.position.x_cm/100.0f, curEst.position.y_cm/100.0f, curEst.position.z_cm/100.0f); - best.add(gpBest); - - gp.draw(plot); - gp.flush(); - */ - } - const int display_ms = 50; + + const int display_ms = Settings::MapView::msPerFrame.ms(); /** UI update loop */ - void display() { + void updateMapViewLoop() { + while(running) { - doDisplay(); + const Timestamp ts1 = Timestamp::fromUnixTime(); + updateMapView(); + const Timestamp ts2 = Timestamp::fromUnixTime(); + const Timestamp tsDiff = ts2-ts1; + const QString mapViewTime = QString::number(tsDiff.ms()); + //QMetaObject::invokeMethod(mainController->getInfoWidget(), "showMapViewTime", Qt::QueuedConnection, Q_ARG(const QString&, mapViewTime)); std::this_thread::sleep_for(std::chrono::milliseconds(display_ms)); } } @@ -264,8 +355,8 @@ private: Point3 curPosSlow; - - void doDisplay() { + /** update the map-view (called from within a background-loop) */ + void updateMapView() { const float kappa1 = display_ms / 1000.0f; const float kappa2 = kappa1 * 0.7; @@ -278,19 +369,21 @@ private: const Point3 dir = (curPosFast - curPosSlow).normalized(); const Point3 dir2 = Point3(dir.x, dir.y, -0.2).normalized(); + // how to update the camera if (cameraMode == 0) { - mainController->getMapView()->setLookAt(curPosFast + Point3(0,0,myHeight_m), dir); + mainController->getMapView3D()->setLookAt(curPosFast + Point3(0,0,myHeight_m), dir); } else if (cameraMode == 1) { - mainController->getMapView()->setLookAt(curPosFast + Point3(0,0,myHeight_m) - dir2*4, dir2); + mainController->getMapView3D()->setLookAt(curPosFast + Point3(0,0,myHeight_m) - dir2*4, dir2); } else if (cameraMode == 2) { - const Point3 spectator = curPosFast + Point3(0,0,20) - dir*15; + const Point3 spectator = curPosFast + Point3(0,0,25) - dir*15; const Point3 spectatorDir = (curPosFast - spectator).normalized(); - mainController->getMapView()->setLookEye(spectator); - mainController->getMapView()->setLookDir(spectatorDir); + mainController->getMapView3D()->setLookEye(spectator); + mainController->getMapView3D()->setLookDir(spectatorDir); } - mainController->getMapView()->setCurrentEstimation(curPosFast, dir); - + mainController->getMapView3D()->setClipAbove(curEst.position.inMeter().z + 2); + mainController->getMapView3D()->setCurrentEstimation(curEst.position.inMeter(), dir); + mainController->getMapView2D()->setCurrentEstimation(curEst.position.inMeter(), dir); } diff --git a/nav/NavControllerListener.h b/nav/NavControllerListener.h new file mode 100644 index 0000000..19f9f58 --- /dev/null +++ b/nav/NavControllerListener.h @@ -0,0 +1,15 @@ +#ifndef NAVCONTROLLERLISTENER_H +#define NAVCONTROLLERLISTENER_H + +#include + +class NavControllerListener { + +public: + + /** a new position estimation is available */ + virtual void onNewEstimation(const Point3 pos_m) = 0; + +}; + +#endif // NAVCONTROLLERLISTENER_H diff --git a/nav/Node.h b/nav/Node.h index b2be7c0..80b2d0e 100644 --- a/nav/Node.h +++ b/nav/Node.h @@ -4,11 +4,15 @@ #include #include -struct MyGridNode : public GridNode, public GridPoint {//, public WiFiGridNode<10> { +struct MyGridNode : public GridNode, public GridPoint, public WiFiGridNode<20> { float navImportance; float getNavImportance() const { return navImportance; } + float walkImportance; + float getWalkImportance() const { return walkImportance; } + + /** empty ctor */ MyGridNode() : GridPoint(-1, -1, -1) {;} @@ -17,11 +21,11 @@ struct MyGridNode : public GridNode, public GridPoint {//, public WiFiGridNode<1 static void staticDeserialize(std::istream& inp) { - //WiFiGridNode::staticDeserialize(inp); + WiFiGridNode::staticDeserialize(inp); } static void staticSerialize(std::ostream& out) { - //WiFiGridNode::staticSerialize(out); + WiFiGridNode::staticSerialize(out); } }; diff --git a/nav/NodeResampling.h b/nav/NodeResampling.h new file mode 100644 index 0000000..485b515 --- /dev/null +++ b/nav/NodeResampling.h @@ -0,0 +1,123 @@ +#ifndef NODERESAMPLING_H +#define NODERESAMPLING_H + + +#include +#include + +#include +#include + + + /** + * uses simple probability resampling by drawing particles according + * to their current weight. + * HOWEVER: after drawing them, do NOT use them directly, but replace them with a neighbor + * O(log(n)) per particle + */ + template + class NodeResampling : public K::ParticleFilterResampling { + + private: + + /** this is a copy of the particle-set to draw from it */ + std::vector> particlesCopy; + + /** random number generator */ + std::minstd_rand gen; + + Grid& grid; + + public: + + /** ctor */ + NodeResampling(Grid& grid) : grid(grid) { + gen.seed(1234); + } + + void resample(std::vector>& particles) override { + + // compile-time sanity checks + // TODO: this solution requires EXPLICIT overloading which is bad... + //static_assert( HasOperatorAssign::value, "your state needs an assignment operator!" ); + + const uint32_t cnt = (uint32_t) particles.size(); + + // equal weight for all particles. sums up to 1.0 + const double equalWeight = 1.0 / (double) cnt; + + // ensure the copy vector has the same size as the real particle vector + particlesCopy.resize(cnt); + + // swap both vectors + particlesCopy.swap(particles); + + // calculate cumulative weight + double cumWeight = 0; + for (uint32_t i = 0; i < cnt; ++i) { + cumWeight += particlesCopy[i].weight; + particlesCopy[i].weight = cumWeight; + } + +// std::uniform_real_distribution distNewOne(0.0, 1.0); +// std::uniform_int_distribution distRndNode(0, grid.getNumNodes()-1); + std::normal_distribution distTurn(0.0, +0.03); + + // now draw from the copy vector and fill the original one + // with the resampled particle-set + for (uint32_t i = 0; i < cnt; ++i) { + + // slight chance to get a truely random node as particle + // mainly for testing +// if (distNewOne(gen) < 0.005) { +// particles[i].state.position = grid[distRndNode(gen)]; +// particles[i].weight = equalWeight; +// continue; +// } + + // normal redraw procedure + particles[i] = draw(cumWeight); + particles[i].weight = equalWeight; + + const Node* n = grid.getNodePtrFor(particles[i].state.position); + if (n == nullptr) {continue;} // should not happen! + + for (int j = 0; j < 2; ++j) { + std::uniform_int_distribution distIdx(0, n->getNumNeighbors()-1); + const int idx = distIdx(gen); + n = &grid.getNeighbor(*n, idx); + } + + + particles[i].state.position = *n; + particles[i].state.heading.direction += distTurn(gen); + + } + + } + + private: + + /** draw one particle according to its weight from the copy vector */ + const K::Particle& draw(const double cumWeight) { + + // generate random values between [0:cumWeight] + std::uniform_real_distribution dist(0, cumWeight); + + // draw a random value between [0:cumWeight] + const float rand = dist(gen); + + // search comparator (cumWeight is ordered -> use binary search) + auto comp = [] (const K::Particle& s, const float d) {return s.weight < d;}; + auto it = std::lower_bound(particlesCopy.begin(), particlesCopy.end(), rand, comp); + return *it; + + } + + + + }; + + + +#endif // NODERESAMPLING_H diff --git a/nav/State.h b/nav/State.h index 002a30a..726307a 100644 --- a/nav/State.h +++ b/nav/State.h @@ -2,7 +2,7 @@ #define STATE_H #include -#include +#include #include #include #include @@ -10,7 +10,7 @@ #include #include -struct MyState : public WalkState, public WalkStateFavorZ, public WalkStateHeading, public WalkStateBarometerActivity { +struct MyState : public WalkState, public WalkStateFavorZ, public WalkStateHeading { /** ctor */ @@ -52,6 +52,10 @@ struct MyObservation { /** gps measurements */ GPSData gps; + // TODO: switch to a general activity enum/detector for barometer + accelerometer + ...? + /** detected activity */ + ActivityButterPressure::Activity activity; + /** time of evaluation */ Timestamp currentTime; @@ -66,6 +70,10 @@ struct MyControl { /** number of steps since the last transition */ int numStepsSinceLastTransition = 0; + // TODO: switch to a general activity enum/detector using barometer + accelerometer? + /** currently detected activity */ + ActivityButterPressure::Activity activity; + /** reset the control-data after each transition */ void resetAfterTransition() { turnSinceLastTransition_rad = 0; diff --git a/qml.qrc b/qml.qrc index 07cfb98..750cc33 100644 --- a/qml.qrc +++ b/qml.qrc @@ -19,5 +19,7 @@ res/gl/tex/empty_normals.jpg res/icons/cube.svg res/icons/camera.svg + res/icons/wall.svg + res/icons/dots.svg diff --git a/res/gl/fragmentColorPoint.glsl b/res/gl/fragmentColorPoint.glsl index e7fed43..07e2b12 100644 --- a/res/gl/fragmentColorPoint.glsl +++ b/res/gl/fragmentColorPoint.glsl @@ -18,7 +18,7 @@ void main() { #ifdef GL_ES // set point size - gl_PointSize = 3.0; + //gl_PointSize = 3.0; #endif diff --git a/res/gl/fragmentTex.glsl b/res/gl/fragmentTex.glsl index a609dc3..2d5249f 100644 --- a/res/gl/fragmentTex.glsl +++ b/res/gl/fragmentTex.glsl @@ -9,6 +9,7 @@ uniform vec3 lightWorldPos; uniform sampler2D texDiffuse; uniform sampler2D texNormalMap; +uniform float alpha; // interpolated values varying vec3 v_WorldPos; @@ -55,12 +56,12 @@ void main() { // Set fragment color from texture vec4 finalColor = - ambient * 0.05 + - diffuse * 0.95 * diffuseIntensity * lightInt + + ambient * 0.30 + + diffuse * 0.70 * diffuseIntensity * lightInt + clamp(specular * specularIntensity, 0.0, 1.0) * 1.0; gl_FragColor = clamp(finalColor, 0.0, 1.0); - gl_FragColor.a = 0.4; + gl_FragColor.a = alpha; // FOG //float mixing = pow((1.0 - v_CamPos.z * 3.0), 2); diff --git a/res/icons/dots.svg b/res/icons/dots.svg new file mode 100644 index 0000000..37cffbc --- /dev/null +++ b/res/icons/dots.svg @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/icons/wall.svg b/res/icons/wall.svg new file mode 100644 index 0000000..06f68bd --- /dev/null +++ b/res/icons/wall.svg @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sensors/ActivitySensor.h b/sensors/ActivitySensor.h new file mode 100644 index 0000000..0275abf --- /dev/null +++ b/sensors/ActivitySensor.h @@ -0,0 +1,63 @@ +#ifndef BAROMETERACTIVITYSENSOR_H +#define BAROMETERACTIVITYSENSOR_H + +#include +#include "BarometerSensor.h" +#include "AccelerometerSensor.h" + + +struct ActivityData { + const ActivityButterPressure::Activity curActivity; + ActivityData(const ActivityButterPressure::Activity act) : curActivity(act) {;} +}; + +/** + * step-sensor detects steps from the accelerometer + */ +class ActivitySensor : + public SensorListener, // << takes + public SensorListener, // << takes + public Sensor { // << provides + +private: + + ActivityButterPressure act; + + BarometerSensor& baro; + AccelerometerSensor& acc; + +public: + + ActivitySensor(BarometerSensor& baro, AccelerometerSensor& acc) : baro(baro), acc(acc) { + baro.addListener(this); + acc.addListener(this); + } + + virtual void start() override { + // not needed + } + + virtual void stop() override { + // not needed + } + + bool isRunning() const override { + return acc.isRunning() && baro.isRunning(); + } + + virtual void onSensorData(Sensor* sensor, const Timestamp ts, const BarometerData& data) override { + (void) sensor; + const ActivityButterPressure::Activity curAct = act.add(ts, data); + informListeners(ts, ActivityData(curAct)); + } + + virtual void onSensorData(Sensor* sensor, const Timestamp ts, const AccelerometerData& data) override { + (void) sensor; + (void) ts; + (void) data; + // TODO! + } + +}; + +#endif // BAROMETERACTIVITYSENSOR_H diff --git a/sensors/Sensor.h b/sensors/Sensor.h index eee245c..2104e05 100644 --- a/sensors/Sensor.h +++ b/sensors/Sensor.h @@ -33,11 +33,19 @@ public: /** stop this sensor */ virtual void stop() = 0; + /** whether the sensor is currently start()ed */ + virtual bool isRunning() const = 0; + /** add the given listener to the sensor */ void addListener(SensorListener* l) { listeners.push_back(l); } + /** remove the given listener from the sensor */ + void removeListener(SensorListener* l) { + listeners.erase(std::remove(listeners.begin(), listeners.end(), l), listeners.end()); + } + protected: /** inform all attached listeners */ diff --git a/sensors/SensorFactory.h b/sensors/SensorFactory.h index 769c68f..d7acbd1 100644 --- a/sensors/SensorFactory.h +++ b/sensors/SensorFactory.h @@ -22,7 +22,7 @@ #include "StepSensor.h" #include "TurnSensor.h" - +#include "ActivitySensor.h" class SensorFactory { @@ -75,6 +75,12 @@ public: return turns; } + /** get the Activity sensor */ + ActivitySensor& getActivity() { + static ActivitySensor activity(getBarometer(), getAccelerometer()); + return activity; + } + }; #endif // SENSORFACTORY_H diff --git a/sensors/StepSensor.h b/sensors/StepSensor.h index 4078c02..08ce035 100644 --- a/sensors/StepSensor.h +++ b/sensors/StepSensor.h @@ -13,15 +13,18 @@ struct StepData { /** * step-sensor detects steps from the accelerometer */ -class StepSensor : public SensorListener, public Sensor { +class StepSensor : + public SensorListener, // << takes + public Sensor { // << provides private: + AccelerometerSensor& acc; StepDetection sd; public: - StepSensor(AccelerometerSensor& acc) { + StepSensor(AccelerometerSensor& acc) : acc(acc) { acc.addListener(this); } @@ -33,6 +36,10 @@ public: // } + bool isRunning() const override { + return acc.isRunning(); + } + virtual void onSensorData(Sensor* sensor, const Timestamp ts, const AccelerometerData& data) override { (void) sensor; const bool step = sd.add(ts, data); diff --git a/sensors/TurnSensor.h b/sensors/TurnSensor.h index 3da9102..fde34bd 100644 --- a/sensors/TurnSensor.h +++ b/sensors/TurnSensor.h @@ -11,17 +11,23 @@ struct TurnData { TurnData() : radSinceLastEvent(0), radSinceStart(0) {;} }; -class TurnSensor : public SensorListener, public SensorListener, public Sensor { +class TurnSensor : + public SensorListener, // << takes + public SensorListener, // << takes + public Sensor { // << provides private: TurnDetection turn; TurnData data; + AccelerometerSensor& acc; + GyroscopeSensor& gyro; + public: /** ctor */ - TurnSensor(AccelerometerSensor& acc, GyroscopeSensor& gyro) { + TurnSensor(AccelerometerSensor& acc, GyroscopeSensor& gyro) : acc(acc), gyro(gyro) { acc.addListener(this); gyro.addListener(this); } @@ -34,6 +40,10 @@ public: // } + bool isRunning() const override { + return acc.isRunning() && gyro.isRunning(); + } + virtual void onSensorData(Sensor* sensor, const Timestamp ts, const AccelerometerData& data) override { (void) sensor; turn.addAccelerometer(ts, data); diff --git a/sensors/android/AccelerometerSensorAndroid.h b/sensors/android/AccelerometerSensorAndroid.h index 1744860..ed6bb7a 100644 --- a/sensors/android/AccelerometerSensorAndroid.h +++ b/sensors/android/AccelerometerSensorAndroid.h @@ -43,6 +43,10 @@ public: } + bool isRunning() const override { + return acc.isActive(); + } + void stop() override { throw "TODO"; } diff --git a/sensors/android/BarometerSensorAndroid.h b/sensors/android/BarometerSensorAndroid.h index 8befd68..2fcb5c1 100644 --- a/sensors/android/BarometerSensorAndroid.h +++ b/sensors/android/BarometerSensorAndroid.h @@ -33,7 +33,7 @@ public: void start() override { auto onSensorData = [&] () { - BarometerData data(baro.reading()->pressure()); + BarometerData data(baro.reading()->pressure() / 100.0f); // convert Pa to hPa informListeners(data); }; @@ -42,6 +42,10 @@ public: } + bool isRunning() const override { + return baro.isActive(); + } + void stop() override { throw "TODO"; } diff --git a/sensors/android/GyroscopeSensorAndroid.h b/sensors/android/GyroscopeSensorAndroid.h index b42f747..4f33e86 100644 --- a/sensors/android/GyroscopeSensorAndroid.h +++ b/sensors/android/GyroscopeSensorAndroid.h @@ -46,6 +46,10 @@ public: } + bool isRunning() const override { + return gyro.isActive(); + } + void stop() override { throw "TODO"; } diff --git a/sensors/android/WiFiSensorAndroid.cpp b/sensors/android/WiFiSensorAndroid.cpp index 7001439..4f53789 100644 --- a/sensors/android/WiFiSensorAndroid.cpp +++ b/sensors/android/WiFiSensorAndroid.cpp @@ -8,8 +8,7 @@ extern "C" { JNIEXPORT void JNICALL Java_indoor_java_WiFi_onScanComplete(JNIEnv* env, jobject jobj, jbyteArray arrayID) { (void) env; (void) jobj; jsize length = env->GetArrayLength(arrayID); - jboolean isCopy; - jbyte* data = env->GetByteArrayElements(arrayID, &isCopy); + jbyte* data = env->GetByteArrayElements(arrayID, 0); std::string str((char*)data, length); env->ReleaseByteArrayElements(arrayID, data, JNI_ABORT); WiFiSensorAndroid::get().handle(str); diff --git a/sensors/android/WiFiSensorAndroid.h b/sensors/android/WiFiSensorAndroid.h index 96b2f03..1160e85 100644 --- a/sensors/android/WiFiSensorAndroid.h +++ b/sensors/android/WiFiSensorAndroid.h @@ -16,6 +16,8 @@ private: /** hidden ctor. use singleton! */ WiFiSensorAndroid() {;} + bool started = false; + public: /** singleton access */ @@ -28,7 +30,8 @@ public: // start scanning int res = QAndroidJniObject::callStaticMethod("indoor/java/WiFi", "start", "()I"); - (void) res; + if (res != 0) {throw Exception("error while starting WiFi");} + started = true; } @@ -36,8 +39,12 @@ public: throw "todo"; } + bool isRunning() const override { + return started; + } + /** called from java. handle the given incoming scan result */ - void handle(const std::string& data) { + void handle(const std::string data) { // to-be-constructed sensor data WiFiMeasurements sensorData; diff --git a/sensors/dummy/RandomSensor.h b/sensors/dummy/RandomSensor.h index e368946..5f0fa75 100644 --- a/sensors/dummy/RandomSensor.h +++ b/sensors/dummy/RandomSensor.h @@ -31,6 +31,11 @@ public: thread.join(); } + bool isRunning() const override { + return running; + } + + protected: /** subclasses must provide a random entry here */ diff --git a/sensors/dummy/WiFiSensorDummy.h b/sensors/dummy/WiFiSensorDummy.h index 7e09b8b..55c4cd9 100644 --- a/sensors/dummy/WiFiSensorDummy.h +++ b/sensors/dummy/WiFiSensorDummy.h @@ -26,6 +26,9 @@ public: return wifi; } + bool isRunning() const override { + return enabled; + } void start() override { diff --git a/sensors/offline/AllInOneSensor.h b/sensors/offline/AllInOneSensor.h index 542bfd6..a0abbbb 100644 --- a/sensors/offline/AllInOneSensor.h +++ b/sensors/offline/AllInOneSensor.h @@ -37,6 +37,10 @@ public: thread.join(); } + bool isRunning() const override { + return running; + } + protected: virtual void onGyroscope(const Timestamp _ts, const GyroscopeData data) override { diff --git a/tests/RuntimeTests.h b/tests/RuntimeTests.h new file mode 100644 index 0000000..6191d85 --- /dev/null +++ b/tests/RuntimeTests.h @@ -0,0 +1,58 @@ +#ifndef RUNTIMETESTS_H +#define RUNTIMETESTS_H + +#include +#include "ipin/Scaler.h" + +class RuntimeTests { + +public: + + static void run() { + testFingerprint(); + testScaler(); + } + +private: + + static void testScaler() { + + IPINScaler scaler = IPINScaler(1869, 1869, 40.51312440, -3.34959080, -40.73112000, 0.07596002); + + // map center + const float cenX = 1869/2.0*0.07596002; + const float cenY = 1869/2.0*0.07596002; + + const IPIN lonlat = scaler.toIPIN3(cenX, cenY, 0); + Assert::isNear(40.51312440, lonlat.lat, 0.000001, "scaler error"); // lat = up/down + Assert::isNear(-3.34959080, lonlat.lon, 0.000001, "scaler error"); // lon = left/right + Assert::isNear(0.0, lonlat.floorNr, 0.1, "scaler error"); + + const Point3 p3 = scaler.convert3D(lonlat); + Assert::isNear(cenX, p3.x, 0.01f, "scaler error"); + Assert::isNear(cenY, p3.y, 0.01f, "scaler error"); + Assert::isNear(0.0f, p3.z, 0.01f, "scaler error"); + + } + + static void testFingerprint() { + + MACAddress mac1("00:00:00:00:00:01"); + MACAddress mac2("00:00:00:00:00:02"); + + WiFiFingerprint fp; + fp.measurements.entries.push_back( WiFiMeasurement(AccessPoint(mac1), -60)); + fp.measurements.entries.push_back( WiFiMeasurement(AccessPoint(mac1), -62)); + fp.measurements.entries.push_back( WiFiMeasurement(AccessPoint(mac1), -63)); + fp.measurements.entries.push_back( WiFiMeasurement(AccessPoint(mac2), -71)); + fp.measurements.entries.push_back( WiFiMeasurement(AccessPoint(mac2), -72)); + WiFiMeasurements avg = fp.average(); + Assert::equal(2, (int)avg.entries.size(), "size mismatch"); + Assert::isNear(-61.666f, avg.entries[1].rssi, 0.01f, "rssi avg mismatch"); + Assert::isNear(-71.500f, avg.entries[0].rssi, 0.01f, "rssi avg mismatch"); + + } + +}; + +#endif // RUNTIMETESTS_H diff --git a/tools/calibration/WiFiCalibrationDataModel.h b/tools/calibration/WiFiCalibrationDataModel.h new file mode 100644 index 0000000..d36a09a --- /dev/null +++ b/tools/calibration/WiFiCalibrationDataModel.h @@ -0,0 +1,92 @@ +#ifndef WIFICALIBMODEL_H +#define WIFICALIBMODEL_H + +#include + +#include + +class WiFiCalibrationDataModel { + +private: + + /** the file to save the calibration model to */ + std::string file; + + /** all fingerprints (position -> measurements) within the model */ + std::vector fingerprints; + +public: + + WiFiCalibrationDataModel(const std::string& file) : file(file) { + load(); + } + + const std::vector& getFingerprints() { + return fingerprints; + } + + /** deserialize the model */ + void load() { + + // open and check + std::ifstream inp(file.c_str()); + if (inp.bad() || inp.eof() || ! inp.is_open()) { return; } + + // read all entries + while (!inp.eof()) { + + // each section starts with [fingerprint] + std::string section; + inp >> section; + if (inp.eof()) {break;} + if (section != "[fingerprint]") {throw Exception("error!");} + + // deserialize it + WiFiFingerprint wfp; + wfp.read(inp); + fingerprints.push_back(wfp); + + } + + inp.close(); + + } + + + /** serialize the model */ + void save() { + + // open and check + std::ofstream out(file.c_str()); + if (out.bad()) {throw Exception("error while opening " + file + " for write");} + + // write all entries + for (const WiFiFingerprint& wfp : fingerprints) { + out << "[fingerprint]\n"; + wfp.write(out); + } + + // done + out.close(); + + } + + /** get the fingerprint for the given location. if no fingerprint exists, an empty one is created! */ + WiFiFingerprint& getFingerprint(const Point3 pos_m) { + + // try to find an existing one + for (WiFiFingerprint& wfp : fingerprints) { + // get within range of floating-point rounding issues + if (wfp.pos_m.getDistance(pos_m) < 0.001) {return wfp;} + } + + // create a new one and return its reference + WiFiFingerprint wfp(pos_m); + fingerprints.push_back(wfp); + return fingerprints.back(); + + } + +}; + +#endif // WIFICALIBMODEL_H diff --git a/tools/calibration/WiFiCalibrationScanDialog.cpp b/tools/calibration/WiFiCalibrationScanDialog.cpp new file mode 100644 index 0000000..648fbfa --- /dev/null +++ b/tools/calibration/WiFiCalibrationScanDialog.cpp @@ -0,0 +1,51 @@ +#include "WiFiCalibrationScanDialog.h" + + +WiFiCalibrationScanDialog::WiFiCalibrationScanDialog(WiFiFingerprint& model) : model(model) { + + dlg->resize(300, 300); + + QGridLayout* lay = new QGridLayout(dlg); + + int row = 0; + + QPushButton* btnClear = new QPushButton(dlg); + btnClear->setText("clear"); + btnClear->connect(btnClear, &QPushButton::clicked, [&] () {clear();}); + lay->addWidget(btnClear, row, 0, 1, 1); + + QPushButton* btnRecord = new QPushButton(dlg); + btnRecord->setText("rec"); + btnRecord->connect(btnRecord, &QPushButton::clicked, [&] () {startRecord();}); + lay->addWidget(btnRecord, row, 2, 1, 1); + + ++row; + + lay->addWidget(new QLabel("point"), row, 0, 1, 1); + lblPoint = new QLabel(); + lay->addWidget(lblPoint, row, 1, 1, 2); + + ++row; + + lay->addWidget(new QLabel("stats"), row, 0, 1, 1); + lblStats = new QLabel(); + lay->addWidget(lblStats, row, 1, 1, 2); + + ++row; + + barProg = new QProgressBar(); + lay->addWidget(barProg, row, 0, 1, 3); + + ++row; + + QPushButton* btnCancel = new QPushButton(dlg); + btnCancel->setText("cancel"); + btnCancel->connect(btnCancel, &QPushButton::clicked, [&] () {close();}); + lay->addWidget(btnCancel, row, 0, 1, 1); + + QPushButton* btnOK = new QPushButton(dlg); + btnOK->setText("OK"); + btnOK->connect(btnOK, &QPushButton::clicked, [&] () {save(); close();}); + lay->addWidget(btnOK, row, 2, 1, 1); + +} diff --git a/tools/calibration/WiFiCalibrationScanDialog.h b/tools/calibration/WiFiCalibrationScanDialog.h new file mode 100644 index 0000000..2999e11 --- /dev/null +++ b/tools/calibration/WiFiCalibrationScanDialog.h @@ -0,0 +1,102 @@ +#ifndef CALIBDIALOG_H +#define CALIBDIALOG_H + +#include +#include +#include +#include +#include +#include + +#include "../sensors/SensorFactory.h" +#include "../tools/calibration/WiFiCalibrationDataModel.h" + + + +/** + * show a dialog to perform a WiFiScan + */ +class WiFiCalibrationScanDialog : public QObject, public SensorListener { + + Q_OBJECT + +private: + + QDialog* dlg = new QDialog(); + QLabel* lblStats; + QLabel* lblPoint; + QProgressBar* barProg; + + struct Scan { + const int numRecords = 10; + int recordsDone = 0; + } scan; + + /** the measurements model to fill with scan-entries */ + WiFiFingerprint& model; + +public: + + static void get(WiFiFingerprint& model) { + WiFiCalibrationScanDialog dlg(model); + dlg.show(); + } + +private: + + /** ctor */ + WiFiCalibrationScanDialog(WiFiFingerprint& model); + + void show() { + refresh(); + dlg->exec(); + } + + void close() { + stopRecord(); + dlg->close(); + } + + void save() { + //mdl.save();; + } + + Q_INVOKABLE void refresh() { + lblPoint->setText(QString(model.pos_m.asString().c_str())); + lblStats->setText( QString::number(model.measurements.entries.size()) + " RSSI measurements\n" + QString::number(scan.recordsDone) + " scans"); + barProg->setValue(scan.recordsDone); + barProg->setMaximum(scan.numRecords); + } + + void clear() { + model.measurements.entries.clear(); + refresh(); + } + + + void startRecord() { + scan.recordsDone = 0; + SensorFactory::get().getWiFi().addListener(this); + if (!SensorFactory::get().getWiFi().isRunning()) { + SensorFactory::get().getWiFi().start(); + } + } + + void stopRecord() { + SensorFactory::get().getWiFi().removeListener(this); + } + + virtual void onSensorData(Sensor* sensor, const Timestamp ts, const WiFiMeasurements& data) override { + (void) sensor; + (void) ts; + ++scan.recordsDone; + if (scan.recordsDone >= scan.numRecords) {stopRecord();} + model.measurements.entries.insert(model.measurements.entries.end(), data.entries.begin(), data.entries.end()); + QMetaObject::invokeMethod(this, "refresh", Qt::QueuedConnection); + } + + +}; + + +#endif // CALIBDIALOG_H diff --git a/ui/LoggerUI.h b/ui/LoggerUI.h new file mode 100644 index 0000000..b91beb2 --- /dev/null +++ b/ui/LoggerUI.h @@ -0,0 +1,46 @@ +#ifndef LOGGERUI_H +#define LOGGERUI_H + +#include +#include "debug/InfoWidget.h" +#include + +/** send all log-messages to the UI */ +class LoggerUI : public Logger { + +private: + + InfoWidget* iw; + + std::vector lines; + +public: + + /** ctor with the main-menu to show the log within */ + LoggerUI(InfoWidget* iw) : iw(iw) { + lines.push_back(""); + } + + void add(const std::string& str, const bool nl) override { + lines.back() += QString(str.c_str()); + if (nl) {lines.push_back("");} + while(lines.size() > 4) {lines.erase(lines.begin());} + QString qs = getStr(); + QMetaObject::invokeMethod(iw, "showLog", Qt::QueuedConnection, Q_ARG(const QString&, qs)); + QApplication::processEvents(); + //mm->showActivity(getStr()); + } + +private: + + QString getStr() const { + QString str; + for (const QString& line : lines) {str += line + "\n";} + str.remove(str.length()-1, 1); + return str; + } + + +}; + +#endif // LOGGERUI_H diff --git a/ui/MainWindow.cpp b/ui/MainWindow.cpp index 2cf887f..c1fa7ca 100644 --- a/ui/MainWindow.cpp +++ b/ui/MainWindow.cpp @@ -2,33 +2,58 @@ #include -#include "map/MapView.h" +#include "map/3D/MapView3D.h" +#include "map/2D/MapView2D.h" + #include "menu/MainMenu.h" #include "debug/SensorDataWidget.h" +#include "debug/InfoWidget.h" +#include "UIHelper.h" +#include MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { setMinimumHeight(500); setMinimumWidth(500); - mapView = new MapView(this); + mapView3D = new MapView3D(this); + mapView2D = new MapView2D(this); + mainMenu = new MainMenu(this); - sensorWidget = new SensorDataWidget(this); + infoWidget = new InfoWidget(this); + sensorWidget = new SensorDataWidget(this); sensorWidget->setVisible(false); //sensorWidget->setVisible(false); showMaximized(); + sleep(1); + emit resizeEvent(nullptr); + } void MainWindow::resizeEvent(QResizeEvent* event) { - const int w = event->size().width(); - const int h = event->size().height(); + const int w = this->width(); + const int h = this->height(); + + const int menuH = UIHelper::getMainMenuHeight(this); + const int infoH = UIHelper::getInfoHeight(this); + + int y = 0; + + mainMenu->setGeometry(0,y,w,menuH); y += menuH; + infoWidget->setGeometry(0,y,w,infoH); y += infoH; + + mapView3D->setGeometry(0,y,w,h-y); + mapView2D->setGeometry(0,y,w,h-y); + + sensorWidget->setGeometry(0,y,w,h-y); + + mainMenu->resizeEvent(event); + mapView2D->resizeEvent(event); +// infoWidget->resizeEvent(event); - mapView->setGeometry(0,0,w,h); - mainMenu->setGeometry(0,0,w,64); - sensorWidget->setGeometry(0,64,w,h-64); } diff --git a/ui/MainWindow.h b/ui/MainWindow.h index d816bc1..c09930b 100644 --- a/ui/MainWindow.h +++ b/ui/MainWindow.h @@ -3,9 +3,12 @@ #include -class MapView; +class MapView3D; +class MapView2D; + class MainMenu; class SensorDataWidget; +class InfoWidget; class MainWindow : public QWidget { Q_OBJECT @@ -17,21 +20,22 @@ public: private: - MapView* mapView = nullptr; + MapView3D* mapView3D = nullptr; + MapView2D* mapView2D = nullptr; + MainMenu* mainMenu = nullptr; + InfoWidget* infoWidget = nullptr; SensorDataWidget* sensorWidget = nullptr; public: - MapView* getMapView() const {return mapView;} + MapView3D* getMapView3D() const {return mapView3D;} + MapView2D* getMapView2D() const {return mapView2D;} + MainMenu* getMainMenu() const {return mainMenu;} + InfoWidget* getInfoWidget() const {return infoWidget;} SensorDataWidget* getSensorDataWidget() const {return sensorWidget;} - -// void setMapView(QWidget* widget) {mapView = widget; mapView->setParent(this);} -// void setMainMenu(QWidget* widget) {mainMenu = widget; mainMenu->setParent(this);} -// void setSensorWidget(QWidget* widget) {sensorWidget = widget; sensorWidget->setParent(this);} - signals: public slots: diff --git a/ui/UIHelper.h b/ui/UIHelper.h new file mode 100644 index 0000000..70a46c7 --- /dev/null +++ b/ui/UIHelper.h @@ -0,0 +1,39 @@ +#ifndef UIHELPER_H +#define UIHELPER_H + +#include + +class UIHelper { + +public: + + static int getButtonSize(const QObject* window) { + return isLarge(window) ? (48*2) : (48); + } + + static int getMainMenuHeight(const QObject* window) { + return isLarge(window) ? (64*2) : (64); + } + + static int getInfoHeight(const QObject* window) { + return isLarge(window) ? (70*2) : (70); + } + + static int getPlotHeight(const QObject* window) { + return isLarge(window) ? (90*2) : (90); + } + + static int getWifiLabelDistY(const QObject* window) { + return isLarge(window) ? (13*2) : (13); + } + static int getWifiLabelDistX(const QObject* window) { + return isLarge(window) ? (150*2) : (150); + } + + static bool isLarge(const QObject* window) { + return (((QWidget*)window)->height() > 1000); + } + +}; + +#endif // UIHELPER_H diff --git a/ui/debug/InfoWidget.cpp b/ui/debug/InfoWidget.cpp new file mode 100644 index 0000000..ad9e437 --- /dev/null +++ b/ui/debug/InfoWidget.cpp @@ -0,0 +1,67 @@ +#include "InfoWidget.h" + +#include +#include + +#include + +InfoWidget::InfoWidget(QWidget *parent) : QWidget(parent) { + + //setMinimumHeight(32); + //setMaximumHeight(32); + + QGridLayout* lay = new QGridLayout(this); + int row = 0; + int col = 0; + + lblActivity = new QLabel(); + lblActivity->setText("-"); + //lblActivity->setStyleSheet("QLabel { color : white; }"); + //lblActivity->setFont(QFont("courier", 9)); + lay->addWidget(lblActivity, row, col, 1,1,Qt::AlignLeft); ++row; + lblActivity->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); + + lblFilterTime = new QLabel(); + lblFilterTime->setText("-"); + //lblFilterTime->setStyleSheet("QLabel { color : white; }"); + //lblFilterTime->setFont(QFont("courier", 9)); + lay->addWidget(lblFilterTime, row, col, 1,1,Qt::AlignLeft); ++row; + lblFilterTime->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); + +// lblMapViewTime = new QLabel(); +// lblMapViewTime->setText("-"); +// //lblMapViewTime->setStyleSheet("QLabel { color : white; }"); +// //lblMapViewTime->setFont(QFont("courier", 9)); +// lay->addWidget(lblMapViewTime, row, col, 1,1,Qt::AlignLeft); ++row; +// lblMapViewTime->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); + + col = 1; + row = 0; + + lblLog = new QLabel(this); + lblLog->setText("-"); + //lblLog->setStyleSheet("QLabel { color : white; }"); + lblLog->setFont(QFont("Arial", 8)); + lay->addWidget(lblLog, row, col, 3, 1); + lblLog->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + + + +} + +void InfoWidget::showActivity(const QString& act) { + lblActivity->setText("Activity: " + act); +} + +void InfoWidget::showFilterTime(const QString& act) { + lblFilterTime->setText("Filtering: " + act); +} + +void InfoWidget::showMapViewTime(const QString& act) { + lblMapViewTime->setText("MapView: " + act); +} + +void InfoWidget::showLog(const QString& info) { + lblLog->setText(info); +} + diff --git a/ui/debug/InfoWidget.h b/ui/debug/InfoWidget.h new file mode 100644 index 0000000..bddb20c --- /dev/null +++ b/ui/debug/InfoWidget.h @@ -0,0 +1,35 @@ +#ifndef INFOWIDGET_H +#define INFOWIDGET_H + +#include + +class QLabel; + +class InfoWidget : public QWidget { + + Q_OBJECT + +private: + + QLabel* lblActivity; + QLabel* lblFilterTime; + QLabel* lblMapViewTime; + QLabel* lblLog; + +public: + + explicit InfoWidget(QWidget *parent = 0); + + Q_INVOKABLE void showActivity(const QString& act); + Q_INVOKABLE void showFilterTime(const QString& act); + Q_INVOKABLE void showMapViewTime(const QString& act); + Q_INVOKABLE void showLog(const QString& info); + + +signals: + +public slots: + +}; + +#endif // INFOWIDGET_H diff --git a/ui/debug/PlotTurns.cpp b/ui/debug/PlotTurns.cpp index 0f69dbd..3b94e59 100644 --- a/ui/debug/PlotTurns.cpp +++ b/ui/debug/PlotTurns.cpp @@ -6,7 +6,9 @@ PlotTurns::PlotTurns(QWidget *parent) : QWidget(parent) { setMinimumWidth(96); setMinimumHeight(96); - resize(96, 96); + //setSizeIncrement(QSize(1,1)); + //setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding)); +// resize(96, 96); // setMaximumWidth(64); // setMaximumHeight(64); diff --git a/ui/debug/PlotTurns.h b/ui/debug/PlotTurns.h index d84fd99..6cc3027 100644 --- a/ui/debug/PlotTurns.h +++ b/ui/debug/PlotTurns.h @@ -19,6 +19,8 @@ public: void add(const Timestamp ts, const TurnData& data); + //QSize sizeHint() const {return QSize(96, 96);} + signals: public slots: diff --git a/ui/debug/PlotWiFiScan.cpp b/ui/debug/PlotWiFiScan.cpp index 1c6462c..45ebadd 100644 --- a/ui/debug/PlotWiFiScan.cpp +++ b/ui/debug/PlotWiFiScan.cpp @@ -3,12 +3,18 @@ #include #include +#include "../UIHelper.h" PlotWiFiScan::PlotWiFiScan(QWidget *parent) : QWidget(parent) { setMinimumWidth(96); setMinimumHeight(96); + + //setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + +// setMaximumHeight(300); +// sets //setAutoFillBackground(false); } @@ -24,13 +30,15 @@ void PlotWiFiScan::paintEvent(QPaintEvent* evt) { (void) evt; QPainter p(this); - const int x0 = 4; const int xw = 150; + const int x0 = 4; const int xw = UIHelper::getWifiLabelDistX(this->parent()); const int y0 = 3; - const int lh = 13; + const int lh = UIHelper::getWifiLabelDistY(this->parent()); int x = x0; int y = y0; + int w = width(); + int h = height(); p.fillRect(0,0,width(),height(),QColor(255,255,255,192)); p.setPen(Qt::black); @@ -45,7 +53,7 @@ void PlotWiFiScan::paintEvent(QPaintEvent* evt) { std::string str = mac + ": " + std::to_string((int)m.getRSSI()); p.drawStaticText(x, y, QStaticText(str.c_str())); y += lh; - if (y > 90) {y = y0; x += xw;} + if (y > this->height()-10) {y = y0; x += xw;} } p.end(); diff --git a/ui/debug/SensorDataWidget.cpp b/ui/debug/SensorDataWidget.cpp index 43dd041..9e8c14e 100644 --- a/ui/debug/SensorDataWidget.cpp +++ b/ui/debug/SensorDataWidget.cpp @@ -9,10 +9,15 @@ #include "PlotTurns.h" #include "PlotWiFiScan.h" +#include "../Settings.h" +#include "../UIHelper.h" -template void removeOld(Data& data, const Timestamp limit) { - if (data.size() < 2) {return;} - while ( (data.back().key - data.front().key) > limit.ms()) { +/** helper method to remove old entries */ +template void removeOld(Data& data, const Data& dataRef, const Timestamp limit) { + if (data.size() == 0) {return;} + if (dataRef.size() == 0) {return;} + while ( (dataRef.back().key - data.front().key) > limit.ms()) { + if (data.size() == 0) {return;} data.remove(0); } } @@ -41,7 +46,7 @@ public: Timestamp lastRefresh; bool needsRefresh(const Timestamp ts) { const Timestamp diff = ts - lastRefresh; - return (diff > Timestamp::fromMS(100)); + return (diff > Settings::SensorDebug::updateEvery); } @@ -68,7 +73,7 @@ public: steps.setColor(colors[2]); steps.setPointSize(8); pc.addPlot(&steps); - const float s = 4.2; + const float s = 4.8; const float ref = 9.81; pc.setValRange(Range(ref-s, ref+s)); } @@ -89,10 +94,10 @@ public: void limit() { const Timestamp limit = Timestamp::fromMS(3000); - removeOld(line[0].getData(), limit); - removeOld(line[1].getData(), limit); - removeOld(line[2].getData(), limit); - removeOld(steps.getData(), limit - Timestamp::fromMS(100)); // remove steps a little before. prevents errors + removeOld(line[0].getData(), line[0].getData(), limit); + removeOld(line[1].getData(), line[0].getData(), limit); + removeOld(line[2].getData(), line[0].getData(), limit); + removeOld( steps.getData(), line[0].getData(), limit); // remove steps a little before. prevents errors } }; @@ -102,7 +107,7 @@ class PlotGyro : public PlotXLines<3> { public: PlotGyro(QWidget* parent) : PlotXLines(parent) { - const float s = 1; + const float s = 1.5; const float ref = 0; pc.setValRange(Range(ref-s, ref+s)); } @@ -119,14 +124,14 @@ public: void limit() { const Timestamp limit = Timestamp::fromMS(3000); - removeOld(line[0].getData(), limit); - removeOld(line[1].getData(), limit); - removeOld(line[2].getData(), limit); + removeOld(line[0].getData(), line[0].getData(), limit); + removeOld(line[1].getData(), line[0].getData(), limit); + removeOld(line[2].getData(), line[0].getData(), limit); } }; -class PlotBaro : public PlotXLines<1> { +class PlotBaro : public PlotXLines<2> { public: @@ -135,55 +140,92 @@ public: } void add(const Timestamp ts, const BarometerData& data) { + + static int skip = 0; + if ((++skip % 8) != 0) {return;} + addLineNode(ts, data.hPa, 0); if (needsRefresh(ts)) { limit(); refresh(ts); } - const float s = 0.5; + const float s = 1.0; const float ref = line[0].getData().front().val; pc.setValRange(Range(ref-s, ref+s)); + } + void add(const Timestamp ts, const ActivityData& data) { + + static int skip = 0; + if ((++skip % 8) != 0) {return;} + + float offset = 0; + switch(data.curActivity) { + case ActivityButterPressure::Activity::DOWN: offset = -0.5; break; + case ActivityButterPressure::Activity::UP: offset = +0.5; break; + case ActivityButterPressure::Activity::STAY: offset = +0.1; break; + } + + addLineNode(ts, line[0].getData().front().val + offset, 1); + if (needsRefresh(ts)) { + limit(); + refresh(ts); + } + + } + + void limit() { - removeOld(line[0].getData(), Timestamp::fromMS(8000)); + // no limit! + //removeOld(line[0].getData(), Timestamp::fromMS(15000)); // 15 second values } }; -class PlotTurn : public QWidget { +//class PlotTurn : public QWidget { -}; +//}; SensorDataWidget::SensorDataWidget(QWidget* parent) : QWidget(parent) { - QGridLayout* lay = new QGridLayout(this); - plotGyro = new PlotGyro(this); plotAcc = new PlotAcc(this); plotBaro = new PlotBaro(this); plotTurn = new PlotTurns(this); plotWiFi = new PlotWiFiScan(this); - lay->addWidget(plotGyro, 0, 0, 1, 4, Qt::AlignTop); - lay->addWidget(plotAcc, 1, 0, 1, 4, Qt::AlignTop); - lay->addWidget(plotBaro, 2, 0, 1, 4, Qt::AlignTop); - lay->addWidget(plotTurn, 3, 0, 1, 1, Qt::AlignTop); - lay->addWidget(plotWiFi, 3, 1, 1, 3, Qt::AlignTop); + // layout setup + lay = new QGridLayout(this); + lay->addWidget(plotGyro, 0, 0, 1, 4); + lay->addWidget(plotAcc, 1, 0, 1, 4); + lay->addWidget(plotBaro, 2, 0, 1, 4); + lay->addWidget(plotTurn, 3, 0, 1, 1); + lay->addWidget(plotWiFi, 3, 1, 1, 3); +// lay->setRowStretch(0, 1); +// lay->setRowStretch(1, 1); +// lay->setRowStretch(2, 10); +// lay->setRowStretch(3, 10); +// lay->setVerticalSpacing(5); +// lay->setHorizontalSpacing(5); +// lay->setSizeConstraint(QGridLayout::SetDefaultConstraint); + + // attach as listener to all sensors we want to debug SensorFactory::get().getAccelerometer().addListener(this); SensorFactory::get().getGyroscope().addListener(this); SensorFactory::get().getBarometer().addListener(this); SensorFactory::get().getSteps().addListener(this); SensorFactory::get().getTurns().addListener(this); SensorFactory::get().getWiFi().addListener(this); - - //setAutoFillBackground(false); + SensorFactory::get().getActivity().addListener(this); } + + void SensorDataWidget::onSensorData(Sensor* sensor, const Timestamp ts, const AccelerometerData& data) { (void) sensor; ((PlotAcc*)plotAcc)->add(ts, data); @@ -205,6 +247,11 @@ void SensorDataWidget::onSensorData(Sensor* sensor, const Timesta ((PlotBaro*)plotBaro)->add(ts, data); } +void SensorDataWidget::onSensorData(Sensor* sensor, const Timestamp ts, const ActivityData& data) { + (void) sensor; + ((PlotBaro*)plotBaro)->add(ts, data); +} + void SensorDataWidget::onSensorData(Sensor* sensor, const Timestamp ts, const TurnData& data) { (void) sensor; ((PlotTurns*)plotTurn)->add(ts, data); @@ -214,4 +261,3 @@ void SensorDataWidget::onSensorData(Sensor* sensor, const Time (void) sensor; ((PlotWiFiScan*)plotWiFi)->add(ts, data); } - diff --git a/ui/debug/SensorDataWidget.h b/ui/debug/SensorDataWidget.h index 5c91942..54d0d4a 100644 --- a/ui/debug/SensorDataWidget.h +++ b/ui/debug/SensorDataWidget.h @@ -12,8 +12,10 @@ #include "../sensors/StepSensor.h" #include "../sensors/TurnSensor.h" #include "../sensors/WiFiSensor.h" +#include "../sensors/ActivitySensor.h" class PlotWidget; +class QGridLayout; /** debug display for sensor data */ class SensorDataWidget : @@ -21,6 +23,7 @@ class SensorDataWidget : public SensorListener, public SensorListener, public SensorListener, + public SensorListener, public SensorListener, public SensorListener, public SensorListener { @@ -28,6 +31,7 @@ class SensorDataWidget : Q_OBJECT + public: SensorDataWidget(QWidget* parent); @@ -38,6 +42,7 @@ public: void onSensorData(Sensor* sensor, const Timestamp ts, const StepData& data) override; void onSensorData(Sensor* sensor, const Timestamp ts, const TurnData& data) override; void onSensorData(Sensor* sensor, const Timestamp ts, const WiFiMeasurements& data) override; + void onSensorData(Sensor* sensor, const Timestamp ts, const ActivityData& data) override; private: @@ -47,6 +52,8 @@ private: QWidget* plotTurn; QWidget* plotWiFi; + QGridLayout* lay; + }; diff --git a/ui/dialog/LoadSetupDialog.cpp b/ui/dialog/LoadSetupDialog.cpp index b7ddc00..a15a188 100644 --- a/ui/dialog/LoadSetupDialog.cpp +++ b/ui/dialog/LoadSetupDialog.cpp @@ -1,4 +1,5 @@ #include "LoadSetupDialog.h" +#include "../misc/fixc11.h" #include #include @@ -10,13 +11,12 @@ #include #include - -#include "../Config.h" +#include "../Settings.h" LoadSetupDialog::LoadSetupDialog() { // the folder all map-setups reside within - const std::string base = Config::getMapDir(); + const std::string base = Settings::Data::getMapDir(); QDir mapFolder(QString(base.c_str())); // sanity check. folder must exist diff --git a/ui/map/2D/ColorPoints2D.h b/ui/map/2D/ColorPoints2D.h new file mode 100644 index 0000000..0d477e1 --- /dev/null +++ b/ui/map/2D/ColorPoints2D.h @@ -0,0 +1,120 @@ +#ifndef COLORPOINTS2D_H +#define COLORPOINTS2D_H + +#include +#include "Renderable2D.h" +#include + +#include + +#include +#include "../nav/Node.h" +#include "../nav/State.h" + +/** + * debug color points + */ +class ColorPoints2D : public Renderable2D { + +private: + + struct PT { + Point3 pos; + QColor color; + PT(const Point3 pos, const QColor color) : pos(pos), color(color) {;} + }; + + std::vector points; + +public: + + /** ctor */ + ColorPoints2D() { + + } + + void showGridImportance(Grid* grid) { + + float min = +INFINITY; + float max = -INFINITY; + + for (const MyGridNode& n : *grid) { + const float f = n.getWalkImportance(); + if (f < min) {min = f;} + if (f > max) {max = f;} + } + + max = 1.2; + + for (const MyGridNode& n : *grid) { + const Point3 pt(n.x_cm/100.0f, n.y_cm/100.0f + 0.1f, n.z_cm/100.0f); + const float f = n.getWalkImportance(); + float h = 0.66 - ((f-min)/(max-min)) * 0.66; // 0.66 is blue on the HSV-scale + if (h < 0) {h = 0;} + if (h > 1) {h = 1;} + const QColor color = QColor::fromHsvF(h, 1, 1); + points.push_back(PT(pt, color)); + } + + } + + /** NOTE: must be called from Qt's main thread! */ + template void setFromParticles(const std::vector>& particles) { + + points.clear(); + + // group particles by grid-point + std::unordered_map weights; + for (const K::Particle& p : particles) { + const GridPoint gp = p.state.position; + if (weights.find(gp) != weights.end()) {continue;} + weights[gp] += p.weight; + } + + // find min/max + float min = +INFINITY; + float max = -INFINITY; + for (auto it : weights) { + if (it.second > max) {max = it.second;} + if (it.second < min) {min = it.second;} + } + + // draw colored + for (auto it : weights) { + const GridPoint gp = it.first; + const float w = it.second; + const float p = (w-min) / (max-min); // [0:1] + const Point3 pt(gp.x_cm/100.0f, gp.y_cm/100.0f + 0.1f, gp.z_cm/100.0f); + float h = 0.66 - (p*0.66); // 0.66 is blue on the HSV-scale + const QColor color = QColor::fromHsvF(h, 1, 1); + points.push_back(PT(pt, color)); + } + + } + +protected: + + void doRender(QPainter& qp, const Scaler2D& s, const RenderParams2D& r) override { + + QPen pen; + pen.setWidth(4); + + for (const PT& pt : points) { + + if (pt.pos.z < r.clip.belowHeight_m) {continue;} + if (pt.pos.z > r.clip.aboveHeight_m) {continue;} + + const Point2 p2 = s.mapToScreen(pt.pos.xy()); + + pen.setColor(pt.color); + qp.setPen(pen); + qp.drawPoint(p2.x, p2.y); + + } + + } + + +}; + +#endif // COLORPOINTS2D_H diff --git a/ui/map/2D/Floor2D.h b/ui/map/2D/Floor2D.h new file mode 100644 index 0000000..62df59f --- /dev/null +++ b/ui/map/2D/Floor2D.h @@ -0,0 +1,62 @@ +#ifndef FLOOR2D_H +#define FLOOR2D_H + +#include +#include "Renderable2D.h" + +/** + * draw the floor itself (outline, obstacles) + */ +class Floor2D : public Renderable2D { + +private: + + Floorplan::Floor* floor; + +public: + + /** ctor */ + Floor2D(Floorplan::Floor* floor) : floor(floor) { + + } + +protected: + + void doRender(QPainter& qp, const Scaler2D& s, const RenderParams2D& r) override { + + if (floor->atHeight < r.clip.belowHeight_m) {return;} + if (floor->atHeight > r.clip.aboveHeight_m) {return;} + + qp.setPen(Qt::black); + for (const Floorplan::FloorObstacle* obs : floor->obstacles) { + const Floorplan::FloorObstacleLine* line = dynamic_cast(obs); + if (line) {drawLine(qp, s, line);} + } + + qp.setPen(Qt::gray); + for (const Floorplan::FloorOutlinePolygon* poly : floor->outline) { + drawOutline(qp, s, poly); + } + + } + +private: + + void drawLine(QPainter& qp, const Scaler2D& s, const Floorplan::FloorObstacleLine* line) { + const Point2 pt1 = s.mapToScreen(line->from); + const Point2 pt2 = s.mapToScreen(line->to); + qp.drawLine(pt1.x, pt1.y, pt2.x, pt2.y); + } + + void drawOutline(QPainter& qp, const Scaler2D& s, const Floorplan::FloorOutlinePolygon* poly) { + const int num = poly->poly.points.size(); + for (int i = 0; i < num; ++i) { + const Point2 pt1 = s.mapToScreen(poly->poly.points[(i+0)]); + const Point2 pt2 = s.mapToScreen(poly->poly.points[(i+1)%num]); + qp.drawLine(pt1.x, pt1.y, pt2.x, pt2.y); + } + } + +}; + +#endif // FLOOR2D_H diff --git a/ui/map/2D/HasSelectableNodes.h b/ui/map/2D/HasSelectableNodes.h new file mode 100644 index 0000000..bf8c138 --- /dev/null +++ b/ui/map/2D/HasSelectableNodes.h @@ -0,0 +1,20 @@ +#ifndef HASSELECTABLENODES_H +#define HASSELECTABLENODES_H + +#include +#include + +class HasSelectableNodes { + + +public: + + virtual ~HasSelectableNodes() {;} + + virtual std::vector getNodes() const = 0; + + virtual void selectNode(const int idx) = 0; + +}; + +#endif // HASSELECTABLENODES_H diff --git a/ui/map/2D/MapView2D.cpp b/ui/map/2D/MapView2D.cpp new file mode 100644 index 0000000..e0bc644 --- /dev/null +++ b/ui/map/2D/MapView2D.cpp @@ -0,0 +1,184 @@ +#include "MapView2D.h" + +#include +#include +#include +#include + +#include + +#include "Floor2D.h" +#include "ColorPoints2D.h" +#include "Path2D.h" +#include "WiFiCalibTool.h" + +#include "../../Icons.h" +#include "../../UIHelper.h" + + +MapView2D::MapView2D(QWidget *parent) : QWidget(parent) { + + setFocusPolicy(Qt::StrongFocus); + setRenderHeight(0); + + colorPoints = new ColorPoints2D(); + elements.push_back(colorPoints); + + pathToDest = new Path2D(); + pathToDest->setColor(Qt::blue); + pathToDest->setWidth(10); + elements.push_back(pathToDest); + + pathWalked = new Path2D(); + pathToDest->setColor(Qt::black); + pathToDest->setWidth(5); + elements.push_back(pathWalked); + + + // buttons + //menu = new QWidget(this); + QGridLayout* lay = new QGridLayout(this); + int row = 0; + + + lay->addItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding), row, 0, 1, 1); + + ++ row; + +// // map-layer slider +// sldLayer = new QSlider(); +// sldLayer->setOrientation(Qt::Horizontal); +// connect(sldLayer, &QSlider::sliderMoved, this, &MapView2D::onLayerSelect); +// connect(sldLayer, &QSlider::sliderReleased, this, &MapView2D::onLayerSelect); +// lay->addWidget(sldLayer, row, 0, 1, 1); + + // show/hide button + const int bs = UIHelper::getButtonSize(this); + btnColorPoints = new QPushButton(Icons::getIcon("dots", bs), ""); + btnColorPoints->connect(btnColorPoints, &QPushButton::clicked, [&] () {colorPoints->setVisible(!colorPoints->isVisible()); emit update();} ); + lay->addWidget(btnColorPoints, row, 0, 1, 1); + + btnLayerMinus = new QPushButton("-"); + connect(btnLayerMinus, &QPushButton::clicked, this, &MapView2D::onLayerMinus); + lay->addWidget(btnLayerMinus, row, 1, 1, 1); + + btnLayerPlus = new QPushButton("+"); + connect(btnLayerPlus, &QPushButton::clicked, this, &MapView2D::onLayerPlus); + lay->addWidget(btnLayerPlus, row, 2, 1, 1); + + + + +} + +void MapView2D::onLayerSelect() { + setRenderHeight(sldLayer->value()); +} + +void MapView2D::onLayerMinus() { + if (layerHeight_m <= 0) {return;} + layerHeight_m -= 1; + setRenderHeight(layerHeight_m); +} +void MapView2D::onLayerPlus() { + if (layerHeight_m >= 16) {return;} + layerHeight_m += 1; + setRenderHeight(layerHeight_m); +} + +void MapView2D::setMap(WiFiCalibrationDataModel* mdl, Floorplan::IndoorMap* map) { + + for (Floorplan::Floor* floor : map->floors) { + Floor2D* f = new Floor2D(floor); + elements.push_back(f); + } + + wifiCalib = new WiFiCalibTool(mdl, map); + elements.push_back(wifiCalib); + + scaler.setCenterM(Point2(70, 35)); + +} + +void MapView2D::showParticles(const std::vector>* particles) { + this->colorPoints->setFromParticles(*particles); +} + +void MapView2D::setCurrentEstimation(const Point3 pos_m, const Point3 dir) { + (void) dir; + setRenderHeight(pos_m.z); + scaler.setCenterM(pos_m.xy()); +} + +void MapView2D::setRenderHeight(const float height_m) { + renderParams.clip.aboveHeight_m = height_m + 1.5; + renderParams.clip.belowHeight_m = height_m - 1.5; + emit update(); +} + +void MapView2D::showGridImportance(Grid* grid) { + colorPoints->showGridImportance(grid); +} + +void MapView2D::resizeEvent(QResizeEvent* evt) { + (void) evt; + int s = UIHelper::getButtonSize(this->parent()) * 1.5; + //sldLayer->setMinimumHeight(s); + //sldLayer->setMinimum(0); + //sldLayer->setMaximum(16); + btnColorPoints->setMinimumHeight(s); + btnColorPoints->setMinimumWidth(s); + btnLayerMinus->setMinimumHeight(s); + btnLayerMinus->setMinimumWidth(s); + btnLayerPlus->setMinimumHeight(s); + btnLayerPlus->setMinimumWidth(s); + + scaler.setScreenSize(width(), height()); + scaler.setScale( UIHelper::isLarge(this->parent()) ? 2 : 1 ); + +} + +void MapView2D::mousePressEvent(QMouseEvent* evt) { + move.startCenter_px = scaler.getCenterPX(); + move.startMouse_px = Point2(evt->x(), evt->y()); +} + +void MapView2D::mouseMoveEvent(QMouseEvent* evt) { + Point2 pt(evt->x(), evt->y()); + pt -= move.startMouse_px; + pt.x = -pt.x; + pt += move.startCenter_px; + scaler.setCenterPX(pt); + emit update(); +} + +void MapView2D::mouseReleaseEvent(QMouseEvent* evt) { + + if (!wifiCalib) {return;} + + const Point2 p1(evt->x(), evt->y()); + + int idx = 0; + for (const Point2 p2 : wifiCalib->getNodes()) { + const float dist = p1.getDistance(p2); + if (dist < 25) { wifiCalib->selectNode(idx); emit update(); break; } + ++idx; + } + +} + +void MapView2D::paintEvent(QPaintEvent*) { + + QPainter qp(this); + + // clear + qp.fillRect(0, 0, width(), height(), Qt::white); + + // render elements + for (Renderable2D* r : elements) { + r->render(qp, scaler, renderParams); + } + + qp.end(); + +} diff --git a/ui/map/2D/MapView2D.h b/ui/map/2D/MapView2D.h new file mode 100644 index 0000000..8b8c4ae --- /dev/null +++ b/ui/map/2D/MapView2D.h @@ -0,0 +1,131 @@ +#ifndef MAPVIEW2D_H +#define MAPVIEW2D_H + +#include "../misc/fixc11.h" + +#include + +#include "Scaler2D.h" +#include "Path2D.h" +#include "Renderable2D.h" + +#include +#include + +namespace Floorplan { + class IndoorMap; +} + +template class Grid; +class MyGridNode; +class Renderable2D; +class QSlider; +class QPushButton; +class ColorPoints2D; +class Path2D; + +template class DijkstraPath; +namespace K { + template class Particle; +} +class MyState; + +class WiFiCalibTool; +class WiFiCalibrationDataModel; + +class MapView2D : public QWidget { + + Q_OBJECT + +private: + + std::vector elements; + ColorPoints2D* colorPoints = nullptr; + Path2D* pathToDest = nullptr; + Path2D* pathWalked = nullptr; + WiFiCalibTool* wifiCalib = nullptr; + + Scaler2D scaler; + RenderParams2D renderParams; + float layerHeight_m = 0; + + struct Move { + Point2 startCenter_px; + Point2 startMouse_px; + } move; + + QWidget* menu = nullptr; + QSlider* sldLayer = nullptr; + QPushButton* btnColorPoints = nullptr; + QPushButton* btnLayerPlus = nullptr; + QPushButton* btnLayerMinus = nullptr; + +public: + + explicit MapView2D(QWidget *parent = 0); + + /** set the to-be-shown map */ + void setMap(WiFiCalibrationDataModel* mdl, Floorplan::IndoorMap* map); + + /** show importance factors for the grid */ + void showGridImportance(Grid* grid); + + /** set the height-slice to be visible */ + void setRenderHeight(const float height_m); + + + + /** set the path to the destination MUST BE CALLED FROM THE MAIN THREAD */ + void setPathToDestination(const std::vector& path); + + /** set the path to disply. MUST BE CALLED FROM THE MAIN THREAD */ + template void setPathToDestination(const DijkstraPath* path) {this->pathToDest->set(*path);} + + /** set the path to disply. MUST BE CALLED FROM THE MAIN THREAD*/ + Q_INVOKABLE void setPathToDestination(const void* path) { setPathToDestination( (const DijkstraPath*) path); } + + + + /** set the walked path. MUST BE CALLED FROM THE MAIN THREAD */ + void setPathWalked(const std::vector& path) {this->pathWalked->set(path);} + + /** set the walked path. MUST BE CALLED FROM THE MAIN THREAD */ + Q_INVOKABLE void setPathWalked(const void* path) { this->pathWalked->set( *((const std::vector*) path)); } + + + + /** NOTE: must be called from Qt's main thread! */ + Q_INVOKABLE void showParticles(const void* particles) { + showParticles((const std::vector>*) particles); + } + + /** NOTE: must be called from Qt's main thread! */ + void showParticles(const std::vector>* particles); + + + + /** set the currently estimated position */ + void setCurrentEstimation(const Point3 pos, const Point3 dir); + + +signals: + +protected slots: + + void onLayerSelect(); + void onLayerPlus(); + void onLayerMinus(); + +public slots: + + void resizeEvent(QResizeEvent*); + + void paintEvent(QPaintEvent*); + + void mousePressEvent(QMouseEvent*); + void mouseMoveEvent(QMouseEvent*); + void mouseReleaseEvent(QMouseEvent*); + +}; + +#endif // MAPVIEW2D_H diff --git a/ui/map/2D/Path2D.h b/ui/map/2D/Path2D.h new file mode 100644 index 0000000..763f54c --- /dev/null +++ b/ui/map/2D/Path2D.h @@ -0,0 +1,123 @@ +#ifndef PATH2D_H +#define PATH2D_H + + +#include +#include "Renderable2D.h" +#include +#include +#include + +#include "../nav/Node.h" + + +class Path2D : public Renderable2D { + +private: + + /** the path */ + std::vector path; + + float width = 8; + QColor color = Qt::blue; + +public: + + /** ctor */ + Path2D() { + + } + + template void set(const DijkstraPath& path) { + + std::vector out; + for (const DijkstraNode* node : path.getVector()) { + if (!node) {break;} + const Node* elem = node->element; + out.push_back(Point3(elem->x_cm/100.0f, elem->y_cm/100.0f, elem->z_cm/100.0f)); + } + + set(out); + + } + + /** MUST BE CALLED FROM THE MAIN THREAD */ + void set(const std::vector& path) { + this->path = simplify(path); + } + + + /** combine nodes while the direction stays the same (many small quads -> one large quad) */ + std::vector simplify(const std::vector& path) { + + // copy + std::vector out = path; + + // remove unneccesary nodes + for (int i = 1; i < (int) out.size() - 1; ++i) { + + const Point3 pa = out[i-1]; + const Point3 pb = out[i-0]; + const Point3 pc = out[i+1]; + + // same direction as last segment? combine segments! + const float dir1 = std::atan2(pb.y-pa.y, pb.x-pa.x); // last edge + const float dir2 = std::atan2(pc.y-pb.y, pc.x-pb.x); // next edge + const bool isSameDir = std::abs(dir1-dir2) < 0.03; // last-edge and next-edge have (approx) the same direction? + if (isSameDir) {out.erase(out.begin()+i); --i; continue;} // no additional information! remove the center node + + // too many changes in a small space? -> remove some! + const float d1 = pb.getDistance(pa); // distance to last node + const float d2 = pb.getDistance(pc); // distance to next node + const float min = 1.0; + const bool isPackedChange = d1 < min && d2 < min; // both distances below a threshold? + if (isPackedChange) {out.erase(out.begin()+i); --i; continue;} // -> many changes in a small area -> remove current node! + + } + + return out; + + } + + + /** the color to use */ + void setColor(const QColor color) { + this->color = color; + } + + /** the width to use */ + void setWidth(const float w) { + this->width = w; + } + + +protected: + + void doRender(QPainter& qp, const Scaler2D& s, const RenderParams2D& r) override { + + QPen pen; + pen.setWidth(this->width); + pen.setColor(color); + qp.setPen(pen); + + for (int i = 0; i < (int)path.size() - 1; ++i) { + + const Point3 p1 = path[i]; + const Point3 p2 = path[i+1]; + + if (p1.z < r.clip.belowHeight_m && p2.z < r.clip.belowHeight_m) {continue;} + if (p1.z > r.clip.aboveHeight_m && p2.z > r.clip.aboveHeight_m) {continue;} + + const Point2 pa1 = s.mapToScreen(p1.xy()); + const Point2 pa2 = s.mapToScreen(p2.xy()); + + qp.drawLine(pa1.x, pa1.y, pa2.x, pa2.y); + + } + + } + + +}; + +#endif // PATH2D_H diff --git a/ui/map/2D/RenderParams2D.h b/ui/map/2D/RenderParams2D.h new file mode 100644 index 0000000..e303506 --- /dev/null +++ b/ui/map/2D/RenderParams2D.h @@ -0,0 +1,13 @@ +#ifndef RENDERPARAMS2D_H +#define RENDERPARAMS2D_H + +struct RenderParams2D { + + struct Clipping { + float belowHeight_m; + float aboveHeight_m; + } clip; + +}; + +#endif // RENDERPARAMS2D_H diff --git a/ui/map/2D/Renderable2D.h b/ui/map/2D/Renderable2D.h new file mode 100644 index 0000000..5e4810d --- /dev/null +++ b/ui/map/2D/Renderable2D.h @@ -0,0 +1,37 @@ +#ifndef RENDERABLE2D_H +#define RENDERABLE2D_H + +#include +#include "Scaler2D.h" +#include "RenderParams2D.h" + +class Renderable2D { + +private: + + bool visible = true; + +public: + + virtual ~Renderable2D() {;} + + /** show/hide this element */ + void setVisible(const bool visible) {this->visible = visible;} + + /** is this element currently visible? */ + bool isVisible() const {return this->visible;} + + /** render this element */ + void render(QPainter& qp, const Scaler2D& s, const RenderParams2D& p) { + if (!visible) {return;} + doRender(qp, s, p); + } + +protected: + + /** subclasses render themselves here */ + virtual void doRender(QPainter& qp, const Scaler2D& s, const RenderParams2D& p) = 0; + +}; + +#endif // RENDERABLE2D_H diff --git a/ui/map/2D/Scaler2D.h b/ui/map/2D/Scaler2D.h new file mode 100644 index 0000000..e66063e --- /dev/null +++ b/ui/map/2D/Scaler2D.h @@ -0,0 +1,106 @@ +#ifndef SCALER2D_H +#define SCALER2D_H + +#include +#include + +class Scaler2D { + +private: + + Point2 screenSize = Point2(400,400); + Point2 center_m = Point2(0,0); + float rotation_rad = 0.0f; + float scaleFactor = 1; + +public: + + Scaler2D() { + ; + } + + /** set the screen's size (in pixel) */ + void setScreenSize(const float w_px, const float h_px) { + this->screenSize = Point2(w_px, h_px); + } + + /** change the point displayed within the center of the screen */ + void setCenter(const float x_m, const float y_m) { + this->center_m = Point2(x_m, y_m); + } + + /** change the point displayed within the center of the screen */ + void setCenterM(const Point2 center_m) { + this->center_m = center_m; + } + + /** change the point displayed within the center of the screen */ + void setCenterPX(const Point2 center_px) { + this->center_m = pxToM(center_px); + } + + Point2 getCenterPX() const { + return mToPX(this->center_m); + } + + /** set the map's rotation in radians */ + void setRotation(const float rad) { + this->rotation_rad = rad; + } + + void setScale(const float scale) { + this->scaleFactor = scale; + } + + +public: + + float mToPX(const float m) const { + return m * scaleFactor * (screenSize.x * 0.01); + } + + float pxToM(const float px) const { + return px / scaleFactor / (screenSize.x * 0.01); + } + + Point2 pxToM(const Point2 pt) const { + return Point2(pxToM(pt.x), pxToM(pt.y)); + } + + Point2 mToPX(const Point2 pt) const { + return Point2(mToPX(pt.x), mToPX(pt.y)); + } + + /** convert map to screen coordinates */ + Point2 mapToScreen(const Point2 pt_m) const { + + Point2 pt = pt_m; + + // move to (0,0) + pt -= center_m; + + // rotate + pt = Point2( + std::cos(rotation_rad) * pt.x - std::sin(rotation_rad) * pt.y, + std::sin(rotation_rad) * pt.x + std::cos(rotation_rad) * pt.y + ); + + // scale + pt.x = mToPX(pt.x); + pt.y = mToPX(pt.y); + + + // add screen-center + pt += screenSize/2; + + // negate y + pt.y = screenSize.y - pt.y; + + // done + return pt; + + } + +}; + +#endif // SCALER2D_H diff --git a/ui/map/2D/WiFiCalibTool.h b/ui/map/2D/WiFiCalibTool.h new file mode 100644 index 0000000..c3a26ae --- /dev/null +++ b/ui/map/2D/WiFiCalibTool.h @@ -0,0 +1,129 @@ +#ifndef WIFICALIBTOOL_H +#define WIFICALIBTOOL_H + + +#include +#include "Renderable2D.h" + +#include "../../../Settings.h" +#include "HasSelectableNodes.h" + +#include +#include +#include "../../../tools/calibration/WiFiCalibrationDataModel.h" +#include "../../../tools/calibration/WiFiCalibrationScanDialog.h" + +#include +#include +#include "../ui/UIHelper.h" + +#include "../../../sensors/SensorFactory.h" + +struct WiFiCalibPoint { + std::string name; // title + Point3 pos_m; // map position + smartphone height + Point2 pos_px; // screen position + WiFiCalibPoint(const std::string& name, const Point3 pos_m, const Point2 pos_px) : name(name), pos_m(pos_m), pos_px(pos_px) {;} + WiFiCalibPoint() {;} +}; + +/** + * helper for wifi calibration + */ +class WiFiCalibTool : public Renderable2D { + +private: + + WiFiCalibrationDataModel* mdl; + Floorplan::IndoorMap* map; + + std::vector currentlyVisible; + WiFiCalibPoint currentlySelected; + + +public: + + /** ctor */ + WiFiCalibTool(WiFiCalibrationDataModel* mdl, Floorplan::IndoorMap* map) : mdl(mdl), map(map) { + + } + + virtual void selectNode(const int idx) { + currentlySelected = currentlyVisible[idx]; + showCalib(currentlySelected); + } + + /** get all selectable caliration nodes */ + virtual std::vector getNodes() const { + std::vector pts; + for (const WiFiCalibPoint& cp : currentlyVisible) {pts.push_back(cp.pos_px);} + return pts; + } + +protected: + + void doRender(QPainter& qp, const Scaler2D& s, const RenderParams2D& r) override { + + currentlyVisible.clear(); + const QFont font("Arial", 10); + qp.setFont(font); + + for (const Floorplan::Floor* floor : map->floors) { + for (const Floorplan::Beacon* beacon : floor->beacons) { + + const Point3 p = beacon->pos + Point3(0,0,floor->atHeight) + Point3(0,0,Settings::smartphoneAboveGround); + const Point2 pt = s.mapToScreen(p.xy()); + + if (floor->atHeight < r.clip.belowHeight_m) {continue;} + if (floor->atHeight > r.clip.aboveHeight_m) {continue;} + + const WiFiCalibPoint cp(beacon->name, p, pt); + currentlyVisible.push_back(cp); + + const WiFiFingerprint& fp = mdl->getFingerprint(cp.pos_m); + const QString txt1(beacon->name.c_str()); + const QString txt2 = QString::number(fp.measurements.entries.size()); + qp.setPen(Qt::black); + + if (currentlySelected.name == cp.name) { + qp.setBrush(Qt::blue); + } else { + qp.setBrush(Qt::NoBrush); + } + + //FONT SIZE?? + + + int s = 20; + qp.drawEllipse(pt.x-s, pt.y-s, s*2, s*2); + qp.drawText(pt.x+s*2, pt.y-s, txt1); + qp.drawText(pt.x+s*2, pt.y+s, txt2); + + } + } + + } + + + + +private: + + + + void showCalib(const WiFiCalibPoint& cp) { + + // get (or create an empty one) the fingerprint for this location + WiFiFingerprint& fp = mdl->getFingerprint(cp.pos_m); + + // edit it (blocking!) + WiFiCalibrationScanDialog::get(fp); + + // save the model + mdl->save(); + + } + +}; + +#endif // WIFICALIBTOOL_H diff --git a/ui/map/FloorRenderer.h b/ui/map/3D/FloorRenderer.h similarity index 100% rename from ui/map/FloorRenderer.h rename to ui/map/3D/FloorRenderer.h diff --git a/ui/map/MapView.cpp b/ui/map/3D/MapView3D.cpp similarity index 53% rename from ui/map/MapView.cpp rename to ui/map/3D/MapView3D.cpp index 2ad4fd9..21a4f6e 100644 --- a/ui/map/MapView.cpp +++ b/ui/map/3D/MapView3D.cpp @@ -1,4 +1,4 @@ -#include "MapView.h" +#include "MapView3D.h" #include #include @@ -12,6 +12,8 @@ #include "elements/ColorPoints.h" #include "elements/Object.h" +#include "../Settings.h" + #include #include @@ -22,34 +24,47 @@ * which is already visible! */ -MapView::MapView(QWidget* parent) : QOpenGLWidget(parent) { +MapView3D::MapView3D(QWidget* parent) : QOpenGLWidget(parent) { }; -void MapView::clear() { +void MapView3D::clear() { for (Renderable* r : elements) {delete r;} elements.clear(); } -void MapView::setMap(Floorplan::IndoorMap* map) { +void MapView3D::setMap(Floorplan::IndoorMap* map) { clear(); if (!isGLInitialized) {throw Exception("openGL is not yet initialized. add mapView to a visible window!");} - // first to be rendered + // first to be rendered -> the colored debug points this->colorPoints = new ColorPoints(); elements.push_back(this->colorPoints); - //leDude = new Object("/mnt/firma/tmp/3D/minion/minion.obj", "/mnt/firma/tmp/3D/minion/minion.png", "", 0.35); - leDude = new Object("/mnt/firma/tmp/3D/gnome/gnome.obj", "/mnt/firma/tmp/3D/gnome/gnome_diffuse.jpg", "/mnt/firma/tmp/3D/gnome/gnome_normal.jpg", 0.033); - //leDude = new Object("/mnt/firma/tmp/3D/squirrel/squirrel.obj", "/mnt/firma/tmp/3D/squirrel/squirrel.jpg", "/mnt/firma/tmp/3D/squirrel/squirrel_normal.jpg", 0.033); - elements.push_back(leDude); + // 2nd is the path to the destination (if any) + this->pathToDest = new Path(); + elements.push_back(this->pathToDest); + this->pathWalked = new Path(); + this->pathWalked->setWidth(0.3); + this->pathWalked->setColor(Qt::yellow); + elements.push_back(this->pathWalked); + + + + // 3rd is the dude, walking along the path + //leDude = new Object("/mnt/firma/tmp/3D/minion/minion.obj", "/mnt/firma/tmp/3D/minion/minion.png", "", 0.35); + //leDude = new Object("/mnt/firma/tmp/3D/gnome/gnome.obj", "/mnt/firma/tmp/3D/gnome/gnome_diffuse.jpg", "/mnt/firma/tmp/3D/gnome/gnome_normal.jpg", 0.033); + //leDude = new Object("/mnt/firma/tmp/3D/squirrel/squirrel.obj", "/mnt/firma/tmp/3D/squirrel/squirrel.jpg", "/mnt/firma/tmp/3D/squirrel/squirrel_normal.jpg", 0.033); + //elements.push_back(leDude); + + // hereafter follows the floorplan (floors, doors, walls, stairs, ..) for (Floorplan::Floor* floor : map->floors) { elements.push_back(new Ground(floor)); elements.push_back(new Walls(floor)); @@ -58,8 +73,7 @@ void MapView::setMap(Floorplan::IndoorMap* map) { elements.push_back(new Doors(floor)); } - this->path = new Path(); - elements.push_back(this->path); + @@ -73,16 +87,20 @@ void MapView::setMap(Floorplan::IndoorMap* map) { } -void MapView::setPath(const std::vector& path) { - this->path->set(path); +void MapView3D::setPathToDestination(const std::vector& path) { + this->pathToDest->set(path); +} + +void MapView3D::setPathWalked(const std::vector& path) { + this->pathWalked->set(path); } -void MapView::timerEvent(QTimerEvent *) { +void MapView3D::timerEvent(QTimerEvent *) { update(); } -void MapView::initializeGL() { +void MapView3D::initializeGL() { initializeOpenGLFunctions(); @@ -91,21 +109,19 @@ void MapView::initializeGL() { glEnable(GL_CULL_FACE); // start background update timer - const int fps = 25; - const int interval = 1000 / fps; - timer.start(interval, this); + timer.start(Settings::MapView::msPerFrame.ms(), this); // OpenGL is now initialized isGLInitialized = true; } -void MapView::paintGL() { +void MapView3D::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); draw(); } -void MapView::resizeGL(int w, int h) { +void MapView3D::resizeGL(int w, int h) { // Calculate aspect ratio qreal aspect = qreal(w) / qreal(h ? h : 1); @@ -123,7 +139,7 @@ void MapView::resizeGL(int w, int h) { } -void MapView::rebuildLookat() { +void MapView3D::rebuildLookat() { // QVector3D qDir(lookAt.dir.x, lookAt.dir.z, lookAt.dir.y); // QVector3D at = QVector3D(lookAt.pos.x, lookAt.pos.z, lookAt.pos.y); // QVector3D eye = at + qDir * 0.1; @@ -136,12 +152,12 @@ void MapView::rebuildLookat() { // lightPos = eye + QVector3D(0.0, 4.0, 0.0); // eyePos = eye; - const Point3 dir = lookAt.getDir(); + const QVector3D qDir = lookAt.getDir(); - QVector3D qDir(dir.x, dir.z, dir.y); - QVector3D eye(lookAt.eye_m.x, lookAt.eye_m.z, lookAt.eye_m.y); - QVector3D at = eye + qDir * 0.5; - QVector3D up = QVector3D(0,1,0); + //QVector3D qDir(dir.x, dir.z, dir.y); + const QVector3D eye = lookAt.eye_m;//(lookAt.eye_m.x, lookAt.eye_m.z, lookAt.eye_m.y); + const QVector3D at = eye + qDir * 0.5; + const QVector3D up = QVector3D(0,1,0); matView.setToIdentity(); matView.lookAt(eye, at, up); lightPos = eye + QVector3D(0.0, 0.5, 0.0) + qDir * 1.2; @@ -151,7 +167,7 @@ void MapView::rebuildLookat() { } -void MapView::setCurrentEstimation(const Point3 pos, const Point3 dir) { +void MapView3D::setCurrentEstimation(const Point3 pos, const Point3 dir) { const float angle = std::atan2(dir.y, dir.x) * 180 / M_PI; if (leDude) { leDude->setPosition(pos.x, pos.y, pos.z); @@ -159,72 +175,100 @@ void MapView::setCurrentEstimation(const Point3 pos, const Point3 dir) { } } -void MapView::setLookAt(const Point3 pos_m, const Point3 dir) { - lookAt.eye_m = pos_m + dir * 0.1; - lookAt.dir = dir; +void MapView3D::setLookAt(const Point3 pos_m, const Point3 dir) { + lookAt.eye_m = QVector3D(pos_m.x, pos_m.z, pos_m.y) + QVector3D(dir.x, dir.z, dir.y) * 0.1; + lookAt.dir = QVector3D(dir.x, dir.z, dir.y); rebuildLookat(); } -void MapView::setLookDir(const Point3 dir) { - lookAt.dir = dir; +void MapView3D::setLookDir(const Point3 dir) { + lookAt.dir = QVector3D(dir.x, dir.z, dir.y); rebuildLookat(); } -void MapView::setLookEye(const Point3 eye_m) { - lookAt.eye_m = eye_m; +void MapView3D::setLookEye(const Point3 eye_m) { + lookAt.eye_m = QVector3D(eye_m.x, eye_m.z, eye_m.y); rebuildLookat(); } -void MapView::mousePressEvent(QMouseEvent* evt) { +void MapView3D::mousePressEvent(QMouseEvent* evt) { mouseState.down = true; mouseState.x = evt->x(); mouseState.y = evt->y(); } -void MapView::mouseMoveEvent(QMouseEvent* evt) { +void MapView3D::mouseMoveEvent(QMouseEvent* evt) { const float dx = evt->x() - mouseState.x; const float dy = evt->y() - mouseState.y; + mouseState.x = evt->x(); + mouseState.y = evt->y(); // PI*0.3 head movement left/right and up/down - const float yFac = (this->height() / 2) / (M_PI * 0.3); - const float xFac = (this->width() / 2) / (M_PI * 0.3); + //const float yFac = (this->height() / 2) / (M_PI * 0.3); + //const float xFac = (this->width() / 2) / (M_PI * 0.3); + + + const float angleX = dx/3.0f; + const float angleY = dy/3.0f; + lookAt.ax += angleX; + lookAt.ay += angleY; + lookAt.dirRot.setToIdentity(); + lookAt.dirRot.rotate(lookAt.ax, QVector3D(0,1,0)); + lookAt.dirRot.rotate(lookAt.ay, QVector3D(0,0,1)); + + //lookAt.dirRot.rotate(angleX, QVector3D(0,1,0)); + //lookAt.dirRot.rotate(angleY, QVector3D(0,0,1)); - lookAt.dirOffset = Point3(0, std::sin(dx/xFac), std::sin(-dy/yFac)); rebuildLookat(); } -void MapView::mouseReleaseEvent(QMouseEvent* evt) { +void MapView3D::mouseReleaseEvent(QMouseEvent* evt) { + (void) evt; mouseState.down = false; } -void MapView::keyPressEvent(QKeyEvent* evt) { +void MapView3D::keyPressEvent(QKeyEvent* evt) { - if (evt->key() == Qt::Key_W) {lookAt.eye_m += lookAt.getDir(); rebuildLookat();} - if (evt->key() == Qt::Key_S) {lookAt.eye_m -= lookAt.getDir(); rebuildLookat();} + const QVector3D dir = lookAt.getDir() * 0.5; + const QVector3D side(-dir.z(), 0, dir.x()); + if (evt->key() == Qt::Key_W) {lookAt.eye_m += dir; rebuildLookat();} + if (evt->key() == Qt::Key_S) {lookAt.eye_m -= dir; rebuildLookat();} + + if (evt->key() == Qt::Key_A) {lookAt.eye_m += side; rebuildLookat();} + if (evt->key() == Qt::Key_D) {lookAt.eye_m -= side; rebuildLookat();} } -void MapView::toggleRenderMode() { +void MapView3D::toggleRenderMode() { - renderMode = (RenderMode) (((int)renderMode + 1) % 3); + renderMode = (RenderMode) (((int)renderMode + 1) % 2); // normally %3 but lines crash the smartphone for (Renderable* r : elements) { - if (renderMode == RenderMode::OUTLINE) { - r->setOutlineOnly(true); - } else { - r->setOutlineOnly(false); + switch (renderMode) { + case RenderMode::OUTLINE: + r->setOutlineOnly(true); + r->setTransparent(false); + break; + case RenderMode::TRANSPARENT: + r->setOutlineOnly(false); + r->setTransparent(true); + break; + case RenderMode::NORMAL: + r->setOutlineOnly(false); + r->setTransparent(false); + break; } } } -void MapView::draw() { +void MapView3D::draw() { //const Timestamp ts1 = Timestamp::fromUnixTime(); @@ -232,17 +276,9 @@ void MapView::draw() { glClearColor(0,0,0,1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - if (renderMode == RenderMode::TRANSPARENT) { - glEnable(GL_BLEND); - } else { - glDisable(GL_BLEND); - } - glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); - - for (Renderable* r : elements) { QOpenGLShaderProgram& program = r->getProgram(); @@ -255,7 +291,7 @@ void MapView::draw() { program.setUniformValue("lightWorldPos", lightPos); program.setUniformValue("eyeWorldPos", eyePos); - r->render(); + r->render(renderParams); } diff --git a/ui/map/MapView.h b/ui/map/3D/MapView3D.h similarity index 63% rename from ui/map/MapView.h rename to ui/map/3D/MapView3D.h index 6774e64..d61f2a8 100644 --- a/ui/map/MapView.h +++ b/ui/map/3D/MapView3D.h @@ -26,7 +26,7 @@ class Renderable; class Path; -class MapView : public QOpenGLWidget, protected QOpenGLFunctions { +class MapView3D : public QOpenGLWidget, protected QOpenGLFunctions { Q_OBJECT @@ -38,19 +38,26 @@ private: QVector3D lightPos; QVector3D eyePos; + RenderParams renderParams; QBasicTimer timer; std::vector elements; - Path* path = nullptr; + Path* pathToDest = nullptr; + Path* pathWalked = nullptr; ColorPoints* colorPoints = nullptr; Object* leDude = nullptr; struct LookAt { - Point3 eye_m = Point3(0,0,1); - Point3 dir = Point3(1,0,-0.1); - Point3 dirOffset = Point3(0,0,0); - Point3 getDir() const {return dir + dirOffset;} + QVector3D eye_m = QVector3D(0,0,1); + QVector3D dir = QVector3D(1,0,-0.1); + float ax = 0; + float ay = 0; + QMatrix4x4 dirRot; + QVector3D getDir() const {return this->dirRot * this->dir;} + LookAt() { + dirRot.setToIdentity(); + } } lookAt; struct MouseState { @@ -63,9 +70,10 @@ private: void clear(); + public: - MapView(QWidget* parent = 0); + MapView3D(QWidget* parent = 0); /** set the map to display */ void setMap(Floorplan::IndoorMap* map); @@ -79,24 +87,33 @@ public: /** set the eye's position (looking from here) */ void setLookEye(const Point3 eye_m); + /** do not render elements higher than the given height */ + void setClipAbove(const float height_m) {renderParams.clipAboveHeight_m = height_m;} + /** set the currently estimated position */ void setCurrentEstimation(const Point3 pos, const Point3 dir); - /** set the path to disply */ - void setPath(const std::vector& path); - /** NOTE: must be called from Qt's main thread! */ - /** set the path to disply */ - Q_INVOKABLE void setPath(const void* path) { - setPath( (const DijkstraPath*) path); - } + /** set the path to the destination MUST BE CALLED FROM THE MAIN THREAD */ + void setPathToDestination(const std::vector& path); + + /** set the path to disply. MUST BE CALLED FROM THE MAIN THREAD */ + template void setPathToDestination(const DijkstraPath* path) {this->pathToDest->set(*path);} + + /** set the path to disply. MUST BE CALLED FROM THE MAIN THREAD*/ + Q_INVOKABLE void setPathToDestination(const void* path) { setPathToDestination( (const DijkstraPath*) path); } + + + /** set the walked path. MUST BE CALLED FROM THE MAIN THREAD */ + void setPathWalked(const std::vector& path); + + /** set the walked path. MUST BE CALLED FROM THE MAIN THREAD */ + Q_INVOKABLE void setPathWalked(const void* path) { this->pathWalked->set( *((const std::vector*) path)); } + + + - /** NOTE: must be called from Qt's main thread! */ - /** set the path to disply */ - template void setPath(const DijkstraPath* path) { - this->path->set(*path); - } /** NOTE: must be called from Qt's main thread! */ void showGridImportance(Grid* grid) { diff --git a/ui/map/3D/RenderParams.h b/ui/map/3D/RenderParams.h new file mode 100644 index 0000000..27f8668 --- /dev/null +++ b/ui/map/3D/RenderParams.h @@ -0,0 +1,11 @@ +#ifndef RENDERPARAMS_H +#define RENDERPARAMS_H + +struct RenderParams { + + /** clip (do not render) everything above this height */ + float clipAboveHeight_m = 99999; + +}; + +#endif // RENDERPARAMS_H diff --git a/ui/map/Renderable.h b/ui/map/3D/Renderable.h similarity index 84% rename from ui/map/Renderable.h rename to ui/map/3D/Renderable.h index fb639a6..c96733f 100644 --- a/ui/map/Renderable.h +++ b/ui/map/3D/Renderable.h @@ -2,6 +2,7 @@ #define RENDERABLE_H #include +#include "RenderParams.h" class Renderable { @@ -18,9 +19,9 @@ public: QOpenGLShaderProgram& getProgram() {return program;} /** render the renderable */ - void render() { + void render(const RenderParams& params) { program.bind(); - _render(); + _render(params); } struct ModelMatrix { @@ -54,11 +55,13 @@ public: modelMatrix.update(); } - virtual void setOutlineOnly(const bool outline) {;} + virtual void setOutlineOnly(const bool outline) { (void) outline; } + + virtual void setTransparent(const bool transparent) { (void) transparent; } virtual void initGL() = 0; - virtual void _render() = 0; + virtual void _render(const RenderParams& params) = 0; protected: diff --git a/ui/map/elements/ColorPoints.h b/ui/map/3D/elements/ColorPoints.h similarity index 70% rename from ui/map/elements/ColorPoints.h rename to ui/map/3D/elements/ColorPoints.h index 921cce3..dcad3a9 100644 --- a/ui/map/elements/ColorPoints.h +++ b/ui/map/3D/elements/ColorPoints.h @@ -7,9 +7,10 @@ #include "../gl/GLHelper.h" #include "../gl/GLPoints.h" +//#include "../gl/GLTriangles.h" #include "../Renderable.h" -#include "../../../nav/Node.h" +#include "../../../../nav/Node.h" class ColorPoints : public Renderable { @@ -30,17 +31,28 @@ public: points.clear(); + float min = +INFINITY; + float max = -INFINITY; + + for (const MyGridNode& n : *grid) { + const float f = n.getWalkImportance(); + if (f < min) {min = f;} + if (f > max) {max = f;} + } + + max = 1.2; + for (const MyGridNode& n : *grid) { const QVector3D pt(n.x_cm/100.0f, n.z_cm/100.0f + 0.1f, n.y_cm/100.0f); // swap z and y - const float f = n.getNavImportance(); - float h = 0.66 - (f*0.20); // 0.66 is blue on the HSV-scale + const float f = n.getWalkImportance(); + float h = 0.66 - ((f-min)/(max-min)) * 0.66; // 0.66 is blue on the HSV-scale if (h < 0) {h = 0;} if (h > 1) {h = 1;} const QColor color = QColor::fromHsvF(h, 1, 1); points.addPoint(pt, color); } - size = 3.0f; + size = 8.0f; points.rebuild(); } @@ -54,6 +66,7 @@ public: std::unordered_map weights; for (const K::Particle& p : particles) { const GridPoint gp = p.state.position; + if (weights.find(gp) != weights.end()) {continue;} weights[gp] += p.weight; } @@ -84,11 +97,23 @@ public: // points.addPoint(pt, color); // } - size = 6.0f; + size = 8.0f; points.rebuild(); } +// void addPoint(const QVector3D pt, const QColor color) { + +// const float s = 5 / 100.0f; +// const QVector3D col(color.redF(), color.greenF(), color.blueF()); +// const VertColor vc1(pt + QVector3D(-s, -s, 0), col); +// const VertColor vc2(pt + QVector3D(+s, -s, 0), col); +// const VertColor vc3(pt + QVector3D(+s, +s, 0), col); +// const VertColor vc4(pt + QVector3D(-s, +s, 0), col); + +// points.addQuad(vc1, vc2, vc3, vc4); + +// } void initGL() override { loadShader(":/res/gl/vertex1.glsl", ":/res/gl/fragmentColorPoint.glsl"); @@ -97,9 +122,11 @@ public: } /** render the floor */ - void _render() override { + void _render(const RenderParams& params) override { + + (void) params; //glDisable(GL_DEPTH_TEST); - //glPointSize() + #ifndef ANDROID glPointSize(size); #endif diff --git a/ui/map/elements/Doors.h b/ui/map/3D/elements/Doors.h similarity index 94% rename from ui/map/elements/Doors.h rename to ui/map/3D/elements/Doors.h index d7dd77e..ac1fc01 100644 --- a/ui/map/elements/Doors.h +++ b/ui/map/3D/elements/Doors.h @@ -37,8 +37,13 @@ public: } /** render the floor */ - void _render() override { + void _render(const RenderParams& params) override { + + // skip me? + if (params.clipAboveHeight_m < floor->atHeight) {return;} + doors.render(&program); + } diff --git a/ui/map/elements/Ground.h b/ui/map/3D/elements/Ground.h similarity index 87% rename from ui/map/elements/Ground.h rename to ui/map/3D/elements/Ground.h index 2d391e2..d505b42 100644 --- a/ui/map/elements/Ground.h +++ b/ui/map/3D/elements/Ground.h @@ -7,7 +7,7 @@ #include "../gl/GLLines.h" #include "../Renderable.h" -#include "../../../lib/gpc/Polygon.h" +#include "../../../../lib/gpc/Polygon.h" class Ground : public Renderable { @@ -19,7 +19,9 @@ private: GLTriangles ceiling; GLLines outline; + bool outlineOnly = false; + bool transparent = false; public: @@ -50,7 +52,19 @@ public: } /** render the floor */ - void _render() override { + void _render(const RenderParams& params) override { + + // skip me? + if (params.clipAboveHeight_m < floor->atHeight) {return;} + + if (transparent) { + program.setUniformValue("alpha", 0.5f); + glEnable(GL_BLEND); + } else { + program.setUniformValue("alpha", 1.0f); + glDisable(GL_BLEND); + } + if (outlineOnly) { glLineWidth(5); outline.render(&program); @@ -58,10 +72,14 @@ public: flooring.render(&program); ceiling.render(&program); } + + glDisable(GL_BLEND); + } /** render only the outline? */ void setOutlineOnly(const bool outline) override { + (void) outline; // this->outlineOnly = outline; // if (outlineOnly) { // loadShader(":/res/gl/vertex1.glsl", ":/res/gl/fragmentLine.glsl"); @@ -73,6 +91,10 @@ public: // } } + void setTransparent(const bool transparent) override { + this->transparent = transparent; + } + private: diff --git a/ui/map/elements/Handrails.h b/ui/map/3D/elements/Handrails.h similarity index 93% rename from ui/map/elements/Handrails.h rename to ui/map/3D/elements/Handrails.h index fc22f75..ada21be 100644 --- a/ui/map/elements/Handrails.h +++ b/ui/map/3D/elements/Handrails.h @@ -32,7 +32,8 @@ public: } /** render the floor */ - void _render() override { + void _render(const RenderParams& params) override { + if (params.clipAboveHeight_m < floor->atHeight) {return;} glLineWidth(2); lines.render(&program); } diff --git a/ui/map/elements/Object.h b/ui/map/3D/elements/Object.h similarity index 96% rename from ui/map/elements/Object.h rename to ui/map/3D/elements/Object.h index af0687d..ab6a21c 100644 --- a/ui/map/elements/Object.h +++ b/ui/map/3D/elements/Object.h @@ -66,7 +66,8 @@ public: } /** render the floor */ - void _render() override { + void _render(const RenderParams& params) override { + (void) params; triangles.render(&program); } diff --git a/ui/map/elements/Path.h b/ui/map/3D/elements/Path.h similarity index 53% rename from ui/map/elements/Path.h rename to ui/map/3D/elements/Path.h index e674c0b..758d643 100644 --- a/ui/map/elements/Path.h +++ b/ui/map/3D/elements/Path.h @@ -16,19 +16,24 @@ private: GLTriangles lines; + /** path's width (in meter) */ + float width; + + /** the path's color */ + QVector4D color; + public: /** ctor */ Path() { - ; + setColor(QVector4D(0.0, 0.4, 1.0, 0.6)); + setWidth(0.8); } void initGL() override { loadShader(":/res/gl/vertex1.glsl", ":/res/gl/fragmentLine.glsl"); - program.setUniformValue("color", QVector4D(0.0, 0.4, 1.0, 0.6)); - //loadShader(":/res/gl/vertex1.glsl", ":/res/gl/fragmentTexSimple.glsl"); lines.setDiffuse(":/res/gl/tex/arrows.png"); @@ -36,15 +41,32 @@ public: } + /** set the path's color */ + void setColor(const QVector4D& color) { + this->color = color; + } + + /** set the path's color */ + void setColor(const QColor& color) { + setColor(QVector4D(color.redF(), color.greenF(), color.blueF(), color.alphaF())); + } + + /** set the path's width (in meter) */ + void setWidth(const float width) { + this->width = width; + } + /** render the floor */ - void _render() override { - lines.rebuild(); - glLineWidth(30); - glEnable(GL_BLEND); + void _render(const RenderParams& params) override { + + (void) params; + program.setUniformValue("color", color); + + //glEnable(GL_BLEND); glDisable(GL_CULL_FACE); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + //glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); lines.render(&program); - glDisable(GL_BLEND); + //glDisable(GL_BLEND); glEnable(GL_CULL_FACE); } @@ -59,95 +81,15 @@ public: out.push_back(Point3(elem->x_cm/100.0f, elem->y_cm/100.0f, elem->z_cm/100.0f)); } - out = simplify(out); set(out); } - /* - void setSimple(const std::vector& path) { - - - lines.clear(); - const float s = 0.5; - - Point3 lastDir(0,0,0); - std::vector quads; - - for (int i = 1; i < (int) path.size(); ++i) { - - Point3 pa = path[i-1]; - Point3 pb = path[i-0]; - const Point3 pc(0, 0, 1); - - Point3 dir = pb - pa; dir /= dir.length(); - Point3 perb = cross(pa-pb, pc); perb /= perb.length(); - - const Point3 p1 = pa - perb*s; - const Point3 p2 = pa + perb*s; - const Point3 p3 = pb + perb*s; - const Point3 p4 = pb - perb*s; - - if (dir == lastDir) { - quads.back().p3 = p3; - quads.back().p4 = p4; - } else { - quads.push_back(Floorplan::Quad3(p1,p2,p3,p4)); - } - - lastDir = dir; - -// // produce a small gap between path-lines [will be filled with another quad!] -// pa += dir * 0.6; -// pb -= dir * 0.6; - -// - } - - for (int i = 0; i < (int) quads.size(); ++i) { - - // add the line-segment - const Floorplan::Quad3 q1 = quads[i]; - addQuad(q1); - -// // construct the quad between adjacent segments -// if (i < (int) quads.size() - 1) { -// const Floorplan::Quad3 q2 = quads[i+1]; -// const Floorplan::Quad3 q3(q1.p3, q2.p2, q2.p1, q1.p4); -// addQuad(q3); -// } - - - } - - } - */ - /** combine nodes while the direction stays the same (many small quads -> one large quad) */ std::vector simplify(const std::vector& path) { - std::vector out; - - Point3 lastDir(0,0,0); - if (!path.empty()) { - out.push_back(path.back()); - } - - for (int i = path.size() - 1; i >= 1; --i) { - - const Point3 pa = path[i-0]; - const Point3 pb = path[i-1]; - const Point3 dir = (pb - pa).normalized(); - - if (dir == lastDir) { - out[out.size()-1] = pb; - } else { - out.push_back(pb); - } - - lastDir = dir; - - } + // copy + std::vector out = path; // remove unneccesary nodes for (int i = 1; i < (int) out.size() - 1; ++i) { @@ -156,13 +98,18 @@ public: const Point3 pb = out[i-0]; const Point3 pc = out[i+1]; - const float min = 0.6; - const float d1 = pb.getDistance(pa); - const float d2 = pb.getDistance(pc); + // same direction as last segment? combine segments! + const float dir1 = std::atan2(pb.y-pa.y, pb.x-pa.x); // last edge + const float dir2 = std::atan2(pc.y-pb.y, pc.x-pb.x); // next edge + const bool isSameDir = std::abs(dir1-dir2) < 0.03; // last-edge and next-edge have (approx) the same direction? + if (isSameDir) {out.erase(out.begin()+i); --i; continue;} // no additional information! remove the center node - if (d1 < min || d2 < min) { - out.erase(out.begin() + i); - } + // too many changes in a small space? -> remove some! + const float d1 = pb.getDistance(pa); // distance to last node + const float d2 = pb.getDistance(pc); // distance to next node + const float min = 0.8; + const bool isPackedChange = d1 < min && d2 < min; // both distances below a threshold? + if (isPackedChange) {out.erase(out.begin()+i); --i; continue;} // -> many changes in a small area -> remove current node! } @@ -170,61 +117,16 @@ public: } -// void set(const std::vector& path) { - -// lines.clear(); - -// const float s = 0.4; -// std::vector pts; - -// for (int i = 0; i < (int) path.size(); ++i) { - -// const Point3 pa = path[i-1]; -// const Point3 pb = path[i-0]; -// const Point3 pc(0, 0, 1); - -// const Point3 perb = cross(pa-pb, pc).normalized(); - -// // quad's edges -// const Point3 p1 = pa - perb*s; -// const Point3 p2 = pa + perb*s; -// const Point3 p3 = pb + perb*s; -// const Point3 p4 = pb - perb*s; - -// pts.push_back(p1); -// pts.push_back(p2); - -// } - -// std::vector quads; -// for (int i = 0; i < (int) pts.size(); i+=2) { -// quads.push_back(Floorplan::Quad3(pts[i+0], pts[i+1], pts[i+3], pts[i+2])); -// } - -// float l1 = 0; -// float l2 = 0; - -// for (int i = 0; i < (int) quads.size(); ++i) { - -// // add the line-segment -// const Floorplan::Quad3 q1 = quads[i]; -// l2 += ((q1.p1 + q1.p2) / 2).getDistance( (q1.p3 + q1.p4) / 2 ); -// addQuad(q1, l1, l2); -// l1 = l2; - -// } - -// } - - - - void set(const std::vector& path) { + /** MUST BE CALLED FROM THE MAIN THREAD */ + void set(const std::vector& _path) { + std::vector path = simplify(_path); + // reset lines.clear(); // half the width of the path - const float s = 0.4; + const float s = this->width * 0.5; std::vector quads; for (int i = 1; i < (int) path.size(); ++i) { @@ -275,6 +177,8 @@ public: } + lines.rebuild(); + } private: @@ -306,7 +210,6 @@ private: const VertNormTex vnt3(v3, n, tex3); const VertNormTex vnt4(v4, n, tex4); - lines.addQuadCCW(vnt1, vnt2, vnt3, vnt4); } diff --git a/ui/map/elements/Stairs.h b/ui/map/3D/elements/Stairs.h similarity index 98% rename from ui/map/elements/Stairs.h rename to ui/map/3D/elements/Stairs.h index cf126b2..c6d37ae 100644 --- a/ui/map/elements/Stairs.h +++ b/ui/map/3D/elements/Stairs.h @@ -40,7 +40,8 @@ public: } /** render the floor */ - void _render() override { + void _render(const RenderParams& params) override { + (void) params; parts.render(&program); } diff --git a/ui/map/elements/Walls.h b/ui/map/3D/elements/Walls.h similarity index 88% rename from ui/map/elements/Walls.h rename to ui/map/3D/elements/Walls.h index 93a14a8..27f0d06 100644 --- a/ui/map/elements/Walls.h +++ b/ui/map/3D/elements/Walls.h @@ -17,15 +17,15 @@ private: GLTriangles triangles; GLLines outlines; + bool outlineOnly = false; + bool transparent = false; public: /** ctor */ Walls(Floorplan::Floor* floor) : floor(floor) { - setOutlineOnly(false); - } @@ -42,13 +42,28 @@ public: } /** render the floor */ - void _render() override { + void _render(const RenderParams& params) override { + + // skip me? + if (params.clipAboveHeight_m < floor->atHeight) {return;} + + if (transparent) { + program.setUniformValue("alpha", 0.5f); + glEnable(GL_BLEND); + } else { + program.setUniformValue("alpha", 1.0f); + glDisable(GL_BLEND); + } + if (outlineOnly) { glLineWidth(1); outlines.render(&program); } else { triangles.render(&program); } + + glDisable(GL_BLEND); + } /** render only the outline? */ @@ -64,6 +79,10 @@ public: } } + void setTransparent(const bool transparent) override { + this->transparent = transparent; + } + private: diff --git a/ui/map/gl/GL.h b/ui/map/3D/gl/GL.h similarity index 77% rename from ui/map/gl/GL.h rename to ui/map/3D/gl/GL.h index 3ed907b..4b81019 100644 --- a/ui/map/gl/GL.h +++ b/ui/map/3D/gl/GL.h @@ -20,9 +20,13 @@ struct VertColor { int getVertOffset() const {return 0;} int getColorOffset() const {return sizeof(QVector3D);} int getTanOffset() const {throw "error";} + int getNormOffset() const {throw "error";} + int getTexOffset() const {throw "error";} bool operator == (const VertColor& o) const {return (vert == o.vert) && (color == o.color);} static bool hasTangent() {return false;} static bool hasColor() {return true;} + static bool hasNormal() {return false;} + static bool hasTexCoord() {return false;} }; struct VertNorm { @@ -32,9 +36,12 @@ struct VertNorm { int getVertOffset() const {return 0;} int getNormOffset() const {return sizeof(QVector3D);} int getTanOffset() const {throw "error";} + int getColorOffset() const {throw "error";} bool operator == (const VertNorm& o) const {return (vert == o.vert) && (norm == o.norm);} static bool hasTangent() {return false;} - + static bool hasNormal() {return true;} + static bool hasTexCoord() {return false;} + static bool hasColor() {return false;} }; struct VertNormTex { @@ -46,8 +53,12 @@ struct VertNormTex { int getNormOffset() const {return sizeof(QVector3D);} int getTexOffset() const {return sizeof(QVector3D)*2;} int getTanOffset() const {throw "error";} + int getColorOffset() const {throw "error";} bool operator == (const VertNormTex& o) const {return (vert == o.vert) && (norm == o.norm) && (tex == o.tex);} static bool hasTangent() {return false;} + static bool hasNormal() {return true;} + static bool hasTexCoord() {return true;} + static bool hasColor() {return false;} }; struct VertNormTexTan { @@ -60,8 +71,12 @@ struct VertNormTexTan { int getNormOffset() const {return sizeof(QVector3D);} int getTexOffset() const {return sizeof(QVector3D)*2;} int getTanOffset() const {return sizeof(QVector3D)*2 + sizeof(QVector2D);} + int getColorOffset() const {throw "error";} bool operator == (const VertNormTexTan& o) const {return (vert == o.vert) && (norm == o.norm) && (tex == o.tex) && (tan == o.tan);} static bool hasTangent() {return true;} + static bool hasNormal() {return true;} + static bool hasTexCoord() {return true;} + static bool hasColor() {return false;} }; #endif // HELPER_GL_H diff --git a/ui/map/gl/GLHelper.h b/ui/map/3D/gl/GLHelper.h similarity index 100% rename from ui/map/gl/GLHelper.h rename to ui/map/3D/gl/GLHelper.h diff --git a/ui/map/gl/GLLines.h b/ui/map/3D/gl/GLLines.h similarity index 100% rename from ui/map/gl/GLLines.h rename to ui/map/3D/gl/GLLines.h diff --git a/ui/map/gl/GLPoints.h b/ui/map/3D/gl/GLPoints.h similarity index 74% rename from ui/map/gl/GLPoints.h rename to ui/map/3D/gl/GLPoints.h index 7bc0c27..f155949 100644 --- a/ui/map/gl/GLPoints.h +++ b/ui/map/3D/gl/GLPoints.h @@ -18,7 +18,8 @@ private: std::vector vertices; std::vector indices; - int mode = GL_POINTS; + // use rectangles instead of GL_POINTS + int mode = GL_TRIANGLES; bool initOnce = true; public: @@ -35,9 +36,31 @@ public: /** add a new face to this element */ void addPoint(const QVector3D& pt, const QColor& color) { - indices.push_back(vertices.size()); - QVector3D c(color.redF(), color.greenF(), color.blueF()); - vertices.push_back(VertColor(pt, c)); + + const QVector3D c(color.redF(), color.greenF(), color.blueF()); + + float s = 10 / 100.0f; + + const VertColor vc1(pt + QVector3D(-s, 0, -s), c); + const VertColor vc2(pt + QVector3D(+s, 0, -s), c); + const VertColor vc3(pt + QVector3D(+s, 0, +s), c); + const VertColor vc4(pt + QVector3D(-s, 0, +s), c); + + const int start = vertices.size(); + + vertices.push_back(vc1); + vertices.push_back(vc2); + vertices.push_back(vc3); + vertices.push_back(vc4); + + indices.push_back(start + 3); + indices.push_back(start + 2); + indices.push_back(start + 1); + + indices.push_back(start + 3); + indices.push_back(start + 1); + indices.push_back(start + 0); + } diff --git a/ui/map/gl/GLTriangles.h b/ui/map/3D/gl/GLTriangles.h similarity index 83% rename from ui/map/gl/GLTriangles.h rename to ui/map/3D/gl/GLTriangles.h index f0427b3..a960b83 100644 --- a/ui/map/gl/GLTriangles.h +++ b/ui/map/3D/gl/GLTriangles.h @@ -17,7 +17,7 @@ private: QOpenGLTexture* textures[4]; std::vector vertices; - std::vector indices; + std::vector indices; public: @@ -123,6 +123,9 @@ public: /** render the element */ void render(QOpenGLShaderProgram* program) { + // nothing to-do? + if (indices.empty()) {return;} + // Tell OpenGL which VBOs to use arrayBuf.bind(); indexBuf.bind(); @@ -137,13 +140,17 @@ public: program->setAttributeBuffer(vertLoc, GL_FLOAT, vertices[0].getVertOffset(), 3, sizeof(vertices[0])); // Tell OpenGL programmable pipeline how to locate vertex texture coordinate data - int normLoc = program->attributeLocation("a_normal"); - program->enableAttributeArray(normLoc); - program->setAttributeBuffer(normLoc, GL_FLOAT, vertices[0].getNormOffset(), 3, sizeof(vertices[0])); + if (T::hasNormal()) { + int normLoc = program->attributeLocation("a_normal"); + program->enableAttributeArray(normLoc); + program->setAttributeBuffer(normLoc, GL_FLOAT, vertices[0].getNormOffset(), 3, sizeof(vertices[0])); + } - int texcoordLocation = program->attributeLocation("a_texcoord"); - program->enableAttributeArray(texcoordLocation); - program->setAttributeBuffer(texcoordLocation, GL_FLOAT, vertices[0].getTexOffset(), 2, sizeof(vertices[0])); + if (T::hasTexCoord()) { + int texcoordLocation = program->attributeLocation("a_texcoord"); + program->enableAttributeArray(texcoordLocation); + program->setAttributeBuffer(texcoordLocation, GL_FLOAT, vertices[0].getTexOffset(), 2, sizeof(vertices[0])); + } // bind tangent data? if (T::hasTangent()) { @@ -152,12 +159,18 @@ public: program->setAttributeBuffer(tanLocation, GL_FLOAT, vertices[0].getTanOffset(), 3, sizeof(vertices[0])); } + // bind color data? + if (T::hasColor()) { + int colorLoc = program->attributeLocation("a_color"); + program->enableAttributeArray(colorLoc); + program->setAttributeBuffer(colorLoc, GL_FLOAT, vertices[0].getColorOffset(), 3, sizeof(vertices[0])); + } // texture program->setUniformValue("texture", 0); // Draw cube geometry using indices from VBO 1 - glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, 0); + glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); } diff --git a/ui/map/gl/Shader.h b/ui/map/3D/gl/Shader.h similarity index 100% rename from ui/map/gl/Shader.h rename to ui/map/3D/gl/Shader.h diff --git a/ui/menu/MainMenu.cpp b/ui/menu/MainMenu.cpp index 83ced25..9119b93 100644 --- a/ui/menu/MainMenu.cpp +++ b/ui/menu/MainMenu.cpp @@ -4,12 +4,13 @@ #include #include +#include #include +#include "../UIHelper.h" MainMenu::MainMenu(QWidget* parent) : QWidget(parent) { - setMinimumHeight(64); QGridLayout* lay = new QGridLayout(this); int row = 0; @@ -27,28 +28,50 @@ MainMenu::MainMenu(QWidget* parent) : QWidget(parent) { Assert::isTrue(connect(btnCamera, &QPushButton::clicked, this, &MainMenu::onCameraButton), "connect() failed"); lay->addWidget(btnCamera, row, col, 1,1,Qt::AlignTop); ++col; - btnTransparent = getButton("cube"); + btnTransparent = getButton("wall"); Assert::isTrue(connect(btnTransparent, &QPushButton::clicked, this, &MainMenu::onTransparentButton), "connect() failed"); - lay->addWidget(btnTransparent, row, col, 1,1,Qt::AlignTop); ++col; + lay->addWidget(btnTransparent, row, col, 1,1,Qt::AlignTop); ++col; + + btn3D = getButton("cube"); + Assert::isTrue(connect(btn3D, &QPushButton::clicked, this, &MainMenu::on3DButton), "connect() failed"); + lay->addWidget(btn3D, row, col, 1,1,Qt::AlignTop); ++col; + btnStart = getButton("run"); Assert::isTrue(connect(btnStart, &QPushButton::clicked, this, &MainMenu::onStartButton), "connect() failed"); lay->addWidget(btnStart, row, col, 1,1,Qt::AlignTop); ++col; +} + +static inline void setButtonSize(QPushButton* btn, int size) { + const int border = 4; + btn->setMinimumHeight(size+border); + btn->setMaximumHeight(size+border); + btn->setMinimumWidth(size+border); + btn->setMaximumWidth(size+border); +} + +void MainMenu::resizeEvent(QEvent* evt) { + + const int s = UIHelper::getButtonSize(this->parent()); + setButtonSize(btnLoadMap, s); + setButtonSize(btnDebug, s); + setButtonSize(btnCamera, s); + setButtonSize(btnTransparent, s); + setButtonSize(btnStart, s); + setButtonSize(btn3D, s); + } QPushButton* MainMenu::getButton(const std::string& icon) { - const int size = 48; - const int border = 4; + const int size = UIHelper::getButtonSize(this->parent()); + QPushButton* btn = new QPushButton(Icons::getIcon(icon, size), ""); btn->setIconSize(QSize(size,size)); - btn->setMinimumHeight(size+border); - btn->setMaximumHeight(size+border); - btn->setMinimumWidth(size+border); - btn->setMaximumWidth(size+border); + setButtonSize(btn, size); return btn; diff --git a/ui/menu/MainMenu.h b/ui/menu/MainMenu.h index 43cdb75..f74f4bd 100644 --- a/ui/menu/MainMenu.h +++ b/ui/menu/MainMenu.h @@ -3,6 +3,7 @@ #include +class QLabel; class QPushButton; class MainMenu : public QWidget { @@ -13,6 +14,10 @@ public: /** ctor */ explicit MainMenu(QWidget* parent); +public slots: + + void resizeEvent(QEvent*); + signals: void onLoadButton(); @@ -20,6 +25,7 @@ signals: void onDebugButton(); void onCameraButton(); void onTransparentButton(); + void on3DButton(); private: @@ -30,6 +36,8 @@ private: QPushButton* btnDebug; QPushButton* btnCamera; QPushButton* btnTransparent; + QPushButton* btn3D; + QLabel* lblLog; }; diff --git a/yasmin.pro b/yasmin.pro index 0427bdc..c49b9fe 100644 --- a/yasmin.pro +++ b/yasmin.pro @@ -11,12 +11,19 @@ ANDROID { QT += sensors } +# openMP +QMAKE_CXXFLAGS += -fopenmp +LIBS += -fopenmp + # debug DEFINES += WITH_DEBUG_LOG DEFINES += WITH_ASSERTIONS +QMAKE_CXXFLAGS += -Werror=return-type + CONFIG += c++11 + # use files in ./_android for the project as well ANDROID_PACKAGE_SOURCE_DIR = $$PWD/_android @@ -38,7 +45,6 @@ SOURCES += \ main.cpp \ lib/gpc/gpc.cpp \ ../Indoor/lib/tinyxml/tinyxml2.cpp \ - ui/map/MapView.cpp \ ui/menu/MainMenu.cpp \ ui/MainWindow.cpp \ Controller.cpp \ @@ -48,7 +54,11 @@ SOURCES += \ ui/debug/PlotTurns.cpp \ ui/debug/PlotWiFiScan.cpp \ sensors/android/WiFiSensorAndroid.cpp \ - sensors/linux/WiFiSensorLinuxC.c + sensors/linux/WiFiSensorLinuxC.c \ + ui/debug/InfoWidget.cpp \ + ui/map/3D/MapView3D.cpp \ + ui/map/2D/MapView2D.cpp \ + tools/calibration/WiFiCalibrationScanDialog.cpp RESOURCES += qml.qrc @@ -87,24 +97,27 @@ HEADERS += \ misc/fixc11.h \ sensors/dummy/WiFiSensorDummy.h \ lib/gpc/Polygon.h \ - Stairs.h \ - ui/map/MapView.h \ - ui/map/FloorRenderer.h \ - ui/map/gl/GL.h \ - ui/map/gl/GLHelper.h \ - ui/map/gl/GLLines.h \ - ui/map/gl/GLTriangles.h \ - ui/map/elements/Doors.h \ - ui/map/elements/Ground.h \ - ui/map/elements/Handrails.h \ - ui/map/elements/Path.h \ - ui/map/elements/Stairs.h \ - ui/map/elements/Walls.h \ + ui/map/3D/FloorRenderer.h \ + ui/map/3D/gl/GL.h \ + ui/map/3D/gl/GLHelper.h \ + ui/map/3D/gl/GLLines.h \ + ui/map/3D/gl/GLTriangles.h \ + ui/map/3D/elements/Doors.h \ + ui/map/3D/elements/Ground.h \ + ui/map/3D/elements/Handrails.h \ + ui/map/3D/elements/Path.h \ + ui/map/3D/elements/Stairs.h \ + ui/map/3D/elements/Walls.h \ + ui/map/3D/gl/GLPoints.h \ + ui/map/3D/elements/ColorPoints.h \ + ui/map/3D/RenderParams.h \ + ui/map/3D/Renderable.h \ + ui/map/3D/gl/Shader.h \ + ui/map/3D/elements/Object.h \ ui/Icons.h \ ui/MainWindow.h \ Controller.h \ ui/menu/MainMenu.h \ - Config.h \ ui/dialog/LoadSetupDialog.h \ ui/debug/plot/Axes.h \ ui/debug/plot/Plot.h \ @@ -120,19 +133,42 @@ HEADERS += \ nav/Filter.h \ nav/Node.h \ sensors/linux/WiFiSensorLinuxC.h \ - ui/map/gl/GLPoints.h \ - ui/map/elements/ColorPoints.h \ sensors/offline/SensorFactoryOffline.h \ sensors/dummy/SensorFactoryDummy.h \ sensors/android/SensorFactoryAndroid.h \ - ui/map/gl/Shader.h \ - ui/map/elements/Object.h \ Settings.h \ nav/RegionalResampling.h \ - sensors/offline/AllInOneSensor.h + sensors/offline/AllInOneSensor.h \ + sensors/ActivitySensor.h \ + ui/LoggerUI.h \ + ui/debug/InfoWidget.h \ + ui/UIHelper.h \ + nav/NodeResampling.h \ + ui/map/3D/MapView3D.h \ + ui/map/2D/MapView2D.h \ + ui/map/2D/Floor2D.h \ + ui/map/2D/Scaler2D.h \ + ui/map/2D/Renderable2D.h \ + ui/map/2D/RenderParams2D.h \ + ui/map/2D/ColorPoints2D.h \ + ui/map/2D/Path2D.h \ + ui/map/2D/WiFiCalibTool.h \ + ui/map/2D/HasSelectableNodes.h \ + tools/calibration/WiFiCalibrationDataModel.h \ + tools/calibration/WiFiCalibrationScanDialog.h \ + tests/RuntimeTests.h \ + ipin/StepLogger.h \ + ipin/Scaler.h \ + ipin/Config.h \ + ipin/IPINHelper.h \ + nav/NavControllerListener.h \ + ipin/StepLoggerWrapper.h \ + ipin/StepLoggerWrapperAndroid.h DISTFILES += \ android-sources/src/MyActivity.java \ res/gl/vertex1.glsl \ res/gl/fragment1.glsl \ - res/gl/tex/empty_normals.jpg + res/gl/tex/empty_normals.jpg \ + _android/src/aidl/it/cnr/isti/steplogger/IStepLoggerService.aidl \ + _android/src/StepLoggerClient.java