-
Notifications
You must be signed in to change notification settings - Fork 3
/
MapSerializer.cc
1822 lines (1486 loc) · 45.4 KB
/
MapSerializer.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- c++ -*-
// Copyright 2009 Isis Innovation Limited
/********************************************************************
A Class to serialize and deserialize maps.
Author: Robert Castle, 2009, bob@robots.ox.ac.uk
********************************************************************/
#include "MapSerializer.h"
#include "Map.h"
#include "MapPoint.h"
#include "KeyFrame.h"
#include "ATANCamera.h"
#include <gvars3/GStringUtil.h>
#include "LevelHelpers.h"
#include "MD5Wrapper.h"
#include "Games.h"
#include "Utils.h"
#include <iostream>
#include <iomanip>
#include <cvd/vision.h>
#include <cvd/image_io.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef WIN32
#include "direct.h"
#endif
namespace PTAMM {
using namespace std;
using namespace GVars3;
/**
* Constructor
*/
MapSerializer::MapSerializer( std::vector<Map*> &maps )
: mpMap(NULL),
mvpMaps(maps)
{
}
/**
* Destructor
*/
MapSerializer::~MapSerializer()
{
}
/**
* Lock the current map
* @return success
*/
bool MapSerializer::_LockMap()
{
return mpMap->mapLockManager.LockMap( this );
}
/**
* Unlock the current map
*/
void MapSerializer::_UnlockMap()
{
mpMap->mapLockManager.UnlockMap( this );
}
/**
* Call this to register the thread with a map and
* assign pMap to mpMap.
* @param pMap the map to register with
*/
void MapSerializer::_RegisterWithMap(Map * pMap)
{
if( pMap != NULL ) {
mpMap = pMap;
mpMap->mapLockManager.Register( this );
}
}
/**
* Call this to remove the thread from a map and set mpMap to NULL
*/
void MapSerializer::_UnRegisterWithMap()
{
if( mpMap != NULL ) {
mpMap->mapLockManager.UnRegister( this );
mpMap = NULL;
}
}
/**
* Initialize the map serializer with the command and parameters required.
* The current map is also passed in case this needs to be known.
* @param sCommand The serialization command
* @param sParams The parameters, such as map number and/or path
* @param currentMap the active map
*/
bool MapSerializer::Init( std::string sCommand, std::string sParams, Map ¤tMap )
{
if( isRunning() ) {
cout << "Serialization is currently running. Please try again in a moment." << endl;
return false;
}
mbOK = false;
msCommand = sCommand;
msParams = sParams;
mpInitMap = ¤tMap;
mbOK = true;
return true;
}
/**
* Clear out all of the temp variables used when loading and saving.
* should be called either before or after each map serialization
*/
void MapSerializer::_CleanUp()
{
mmMapPointSaveLUT.clear();
mmKeyFrameSaveLUT.clear();
mmMapPointLoadLUT.clear();
mmKeyFrameLoadLUT.clear();
mmMeasCrossRef.clear();
mvFailureQueueUIDs.clear();
}
/**
* Finish off the keyframe crossreferencing now that all
* keyframes and map points have been loaded.
* @param hRoot root XML handle
* @return success
*/
bool MapSerializer::_CrossReferencing(TiXmlHandle &hRoot)
{
map< KeyFrame*, vector< std::pair< int, Measurement > > >::iterator i;
vector< std::pair< int, Measurement > >::iterator j;
//for each keyframe link up the map points to measurments
for( i = mmMeasCrossRef.begin(); i != mmMeasCrossRef.end(); i++ )
{
KeyFrame * k = (*i).first;
vector< std::pair< int, Measurement > > & vMeas = (*i).second;
for( j = vMeas.begin(); j != vMeas.end(); j++ )
{
MapPoint * mp = _LookupMapPoint( (*j).first );
if( mp == NULL ) {
cerr << "ERROR: Could not find the matching mappoint for the meas cross ref: " << (*j).first << ". continuing" << endl;
}
else {
k->mMeasurements[ mp ] = (*j).second;
}
}
}
vector<std::pair<int, int> >::iterator fq;
KeyFrame * k = NULL;
MapPoint * m = NULL;
for( fq = mvFailureQueueUIDs.begin(); fq != mvFailureQueueUIDs.end(); fq++ )
{
k = _LookupKeyFrame( (*fq).first );
m = _LookupMapPoint( (*fq).second );
if( m != NULL && k != NULL ) {
mpMap->vFailureQueue.push_back( std::pair<KeyFrame *, MapPoint *>( k, m ) );
}
}
return true;
}
/**
* Load a map by loading the map.xml file and the keyframe
* images in sDirName.
* @param sDirName map directory
* @return success
*/
MapSerializer::MapStatus MapSerializer::_LoadMap( std::string sDirName )
{
TiXmlDocument mXMLDoc; //XML file
string sMapFileName = sDirName + "/map.xml";
//load the XML file
if( !mXMLDoc.LoadFile( sMapFileName ) ) {
cerr << "Failed to load " << sMapFileName << ". Aborting." << endl;
return MAP_FAILED;
}
TiXmlHandle hDoc(&mXMLDoc);
TiXmlElement* pElem;
TiXmlHandle hRoot(0);
pElem = hDoc.FirstChildElement().Element();
// should always have a valid root but handle gracefully if it does not
if (!pElem)
{
cerr << "No root handle in XML file " << sMapFileName << endl;
return MAP_FAILED;
}
string sID( MAP_XML_ID );
string sVersion( MAP_VERSION );
string sFileVersion = pElem->Attribute("version");
if( ( sID.compare( pElem->Value() ) != 0 ) &&
( sVersion.compare( sFileVersion ) != 0 ) )
{
cerr << "Invalid XML file. Need a version " << sVersion << " " << sID
<< " XML file. Not a version " << sFileVersion << " " << pElem->Value() << " file." << endl;
return MAP_FAILED;
}
// save this for later
hRoot = TiXmlHandle(pElem);
//////////// Get map lock ////////////
if( !_LockMap() ) {
cerr << "Failed to get map lock" << endl;
return MAP_FAILED;
}
mpMap->Reset(); // Wipe them out. All of them!
// load the keyframes
bool bOK = _LoadKeyFrames( hRoot, sDirName );
if( !bOK ) {
mpMap->Reset();
_UnlockMap();
return MAP_FAILED;
}
// load map points
bOK = _LoadMapPoints( hRoot );
if( !bOK ) {
mpMap->Reset();
_UnlockMap();
return MAP_FAILED;
}
//////////// load the uids for the keyframes and map points in the failure queue ////////////
///@TODO load the mvFailureQueueUIDs
///// cross ref
bOK = _CrossReferencing( hRoot );
if( !bOK ) {
mpMap->Reset();
_UnlockMap();
return MAP_FAILED;
}
//////////// load the game data ////////////
string sGame = hRoot.FirstChild( "Game" ).Element()->Attribute("type");
cout << "Game = " << sGame << endl;
if( sGame != "None" )
{
string sGameDataFile = hRoot.FirstChild( "Game" ).Element()->Attribute("path");
mpMap->pGame = LoadAGame(sGame, sDirName + "/" + sGameDataFile);
}
//all loaded so set map as good.
mpMap->bGood = true;
//////////// relase map lock ////////////
_UnlockMap();
return MAP_OK;
}
/**
* Load a map specified in the sDirName.
* @param pMap the map to load into
* @param sDirName the directory containing the map
* @return success
*/
MapSerializer::MapStatus MapSerializer::LoadMap( Map * pMap, std::string sDirName )
{
MapStatus ms = MAP_OK;
_CleanUp();
if( pMap == NULL ) {
cerr << "LoadMap: got a NULL map pointer. abort" << endl;
return MAP_FAILED;
}
_RegisterWithMap( pMap );
if( sDirName.empty() ) {
cerr << "sDirName is empty" << endl;
ostringstream os;
os << "map" << setfill('0') << setw(6) << mpMap->MapID();
sDirName = os.str();
}
cout << " Attempting to load map directory " << sDirName << "..." << endl;
//check if there is a map currenly in mpMap.
if( ( mpMap->IsGood() || !mpMap->vpKeyFrames.empty() || !mpMap->vpPoints.empty() ))
{
cerr << "Map already exists! Reset the map first." << endl;
_UnRegisterWithMap();
return MAP_EXISTS;
}
//does it exist and is it a dir
#ifdef WIN32
// Get the current working directory:
char* cwdBuffer = _getcwd( NULL, 0 );
if( cwdBuffer == NULL )
{
perror( "Error getting the current working directory: Error with _getcwd in MapSerializer." );
_UnRegisterWithMap();
return MAP_FAILED;
}
//attempt to change working directory
int chdirReturn = _chdir( sDirName.c_str() ); //returns 0 if change was successful, -1 if it dosen't exist
if( chdirReturn == 0 )
{
//restore previous working directory
_chdir( cwdBuffer );
}
else
{
#else
struct stat st;
if( stat( sDirName.c_str(),&st ) != 0 || !S_ISDIR(st.st_mode) ) {
#endif
_UnRegisterWithMap();
return MAP_FAILED;
}
// load the map file and hence the rest of the map
ms = _LoadMap( sDirName );
if( MAP_OK != ms ) {
_UnRegisterWithMap();
return ms;
}
_UnRegisterWithMap();
_CleanUp();
return MAP_OK;
}
/**
* Load a keyframe from the map.xml file and its associated png image.
* @param phKF the XML node
* @param sPath the diectory path containing the keyframe image file
* @param bQueueFrame is it in the queue list
* @return success
*/
bool MapSerializer::_LoadAKeyFrame( TiXmlHandle &phKF, const std::string & sPath, bool bQueueFrame )
{
int uid = -1;
TiXmlElement* kfe = phKF.ToElement();
kfe->QueryIntAttribute("id", &uid);
if( uid == -1 ) {
cerr << " keyframe has no ID. aborting" << endl;
return false;
}
TiXmlElement * pElem = phKF.FirstChild("Image").ToElement();
if( pElem == NULL ) {
return false;
}
//load the image
ostringstream os;
os << sPath << "/" << pElem->Attribute("file");
string sImgFileName = os.str();
CVD::Image<CVD::byte> im;
try {
CVD::img_load( im, sImgFileName );
}
catch(CVD::Exceptions::All err) {
cerr << "Failed to load image " << sImgFileName << ": " << err.what << endl;
return false;
}
//////////////// Read MD5 Hash
string sMD5, sMD5new;
MD5Wrapper md5w;
sMD5 = pElem->Attribute("md5");
//verify the image
md5w.getHashFromData( im.data(), im.totalsize(), sMD5new );
if( sMD5.compare( sMD5new ) != 0 )
{
cerr << "ERROR: the MD5 hash of " << sImgFileName << " does not match the one in xml file" << endl;
cerr << "ERROR: " << sMD5 << " != " << sMD5new << endl;
return false;
}
/////////////// read camera info and set up
pElem = phKF.FirstChild("Camera").ToElement();
if( pElem == NULL ) {
return false;
}
string sCamName = pElem->Attribute("name");
string tmp;
CVD::ImageRef irCamSize;
tmp = pElem->Attribute("size");
sscanf(tmp.c_str(), "%d %d", &irCamSize.x, &irCamSize.y);
///@TODO this is not very robust to changes in the number of parameters
tmp = pElem->Attribute("params");
Vector<NUMTRACKERCAMPARAMETERS> vCamParams;
sscanf(tmp.c_str(), "%lf %lf %lf %lf %lf", &vCamParams[0], &vCamParams[1], &vCamParams[2], &vCamParams[3], &vCamParams[4]);
ATANCamera Camera(sCamName, irCamSize, vCamParams);
KeyFrame * kf = new KeyFrame(Camera);
////////////// create keyframe
kf->MakeKeyFrame_Lite( im );
if(!bQueueFrame) {
//if the frame is in the queue it has not had the rest of the data made.
kf->MakeKeyFrame_Rest();
}
////////////// Populate with stored data
Vector<6> v6KFPose;
tmp = kfe->Attribute("pose");
sscanf(tmp.c_str(), "%lf %lf %lf %lf %lf %lf", &v6KFPose[0], &v6KFPose[1], &v6KFPose[2],
&v6KFPose[3], &v6KFPose[4], &v6KFPose[5]);
kf->se3CfromW = SE3<>::exp( v6KFPose );
int nTmp = 0;
kfe->QueryIntAttribute("fixed", &nTmp);
kf->bFixed = ( nTmp != 0 ? true : false );
pElem = phKF.FirstChild("SceneDepth").ToElement();
pElem->QueryDoubleAttribute("mean", &kf->dSceneDepthMean);
pElem->QueryDoubleAttribute("sigma", &kf->dSceneDepthSigma);
///////////////////// load in cross ref data to temp vars
//measurements
{
TiXmlHandle hMeas = phKF.FirstChild("Measurements");
int nTmp = -1;
string sTmp;
vector< std::pair< int, Measurement > > vMapPointMeas;
int nSize = -1;
hMeas.ToElement()->QueryIntAttribute("size", &nSize);
for(TiXmlElement* pNode = hMeas.FirstChild().Element();
pNode != NULL;
pNode = pNode->NextSiblingElement() )
{
Measurement meas;
int nId = -1;
pNode->QueryIntAttribute("id", &nId);
pNode->QueryIntAttribute("nLevel", &meas.nLevel);
pNode->QueryIntAttribute("bSubPix", &nTmp);
meas.bSubPix = ( nTmp != 0 ? true : false );
sTmp = pNode->Attribute("v2RootPos");
sscanf( sTmp.c_str(), "%lf %lf", &meas.v2RootPos[0], &meas.v2RootPos[1] );
sTmp = pNode->Attribute("v2ImplanePos");
sscanf( sTmp.c_str(), "%lf %lf", &meas.v2ImplanePos[0], &meas.v2ImplanePos[1] );
sTmp = pNode->Attribute("m2CamDerivs");
sscanf( sTmp.c_str(), "%lf %lf %lf %lf", &meas.m2CamDerivs(0,0), &meas.m2CamDerivs(0,1),
&meas.m2CamDerivs(1,0), &meas.m2CamDerivs(1,1));
pNode->QueryIntAttribute("source", (int*)&meas.Source );
vMapPointMeas.push_back( std::pair< int, Measurement >( nId, meas ) );
}
mmMeasCrossRef[ kf ] = vMapPointMeas;
}
/////// now add to map vector. but still need a cross ref
mmKeyFrameLoadLUT[ uid ] = kf;
if( bQueueFrame ) {
mpMap->vpKeyFrameQueue.push_back( kf );
}
else {
mpMap->vpKeyFrames.push_back( kf );
}
return true;
}
/**
* Recursively load each keyframe
* @param hRoot XML node
* @param sPath path where keyframe dir is located
* @return success
*/
bool MapSerializer::_LoadKeyFrames( TiXmlHandle &hRoot, const std::string & sPath )
{
{
int nSize = -1;
TiXmlHandle pNode = hRoot.FirstChild( "KeyFrames" );
pNode.ToElement()->QueryIntAttribute("size", &nSize);
for(TiXmlElement* pElem = pNode.FirstChild().Element();
pElem != NULL;
pElem = pElem->NextSiblingElement() )
{
///@TODO should do empty entry checking
TiXmlHandle hkf( pElem );
if( !_LoadAKeyFrame( hkf, sPath ) ) {
cerr << "Failed to Load keyframe " << pElem->Attribute("id") << ". Abort." << endl;
return false;
}
}
if( (int)mpMap->vpKeyFrames.size() != nSize ) {
cerr << "Loaded the wrong number of keyframes. " << mpMap->vpKeyFrames.size()
<< " instead of " << nSize << ". Aborting" << endl;
return false;
}
}
//////////// load the keyframe queue ////////////
{
int nSize = -1;
TiXmlHandle pNode = hRoot.FirstChild( "KeyFrameQueue" );
pNode.ToElement()->QueryIntAttribute("size", &nSize);
for(TiXmlElement* pElem = pNode.FirstChild().Element();
pElem != NULL;
pElem = pElem->NextSiblingElement() )
{
TiXmlHandle hkf( pElem );
if( !_LoadAKeyFrame( hkf, sPath, true ) ) {
cerr << "Failed to Load queue keyframe " << pElem->Attribute("id") << ". Abort." << endl;
return false;
}
}
if( (int)mpMap->vpKeyFrameQueue.size() != nSize ) {
cerr << "Loaded the wrong number of queue keyframes. " << mpMap->vpKeyFrameQueue.size()
<< " instead of " << nSize << ". Aborting" << endl;
return false;
}
}
return true;
}
/**
* Load a map point
* @param hMP XML node
* @param bQueuePoint is it a main point or a queue point
* @return success
*/
bool MapSerializer::_LoadAMapPoint( TiXmlHandle &hMP, bool bQueuePoint )
{
int uid = -1;
hMP.ToElement()->QueryIntAttribute("id", &uid);
if( uid == -1 ) {
cerr << " keyframe has no ID. aborting" << endl;
return false;
}
//////////////////// fill in map point
MapPoint * mp = new MapPoint();
string sTmp = hMP.ToElement()->Attribute( "position" );
sscanf( sTmp.c_str(), "%lf %lf %lf", &mp->v3WorldPos[0], &mp->v3WorldPos[1], &mp->v3WorldPos[2]);
hMP.ToElement()->QueryIntAttribute( "outlierCount", &mp->nMEstimatorOutlierCount );
hMP.ToElement()->QueryIntAttribute( "inlierCount", &mp->nMEstimatorInlierCount );
TiXmlElement * pElem = hMP.FirstChild("SourceKF").ToElement();
if( pElem == NULL ) {
return false;
}
int nPatchSource = -1;
pElem->QueryIntAttribute( "id", &nPatchSource );
mp->pPatchSourceKF = _LookupKeyFrame( nPatchSource ); //this can be done only if keyframes loaded first
pElem->QueryIntAttribute( "level", &mp->nSourceLevel );
pElem->QueryIntAttribute( "x", &mp->irCenter.x );
pElem->QueryIntAttribute( "y", &mp->irCenter.y );
string sCenter = pElem->Attribute( "Center_NC" );
sscanf( sCenter.c_str(), "%lf %lf %lf", &mp->v3Center_NC[0], &mp->v3Center_NC[1], &mp->v3Center_NC[2]);
string sOneDown = pElem->Attribute( "OneDownFromCenter_NC" );
sscanf( sOneDown.c_str(), "%lf %lf %lf", &mp->v3OneDownFromCenter_NC[0], &mp->v3OneDownFromCenter_NC[1], &mp->v3OneDownFromCenter_NC[2]);
string sOneRight = pElem->Attribute( "OneRightFromCenter_NC" );
sscanf( sOneRight.c_str(), "%lf %lf %lf", &mp->v3OneRightFromCenter_NC[0], &mp->v3OneRightFromCenter_NC[1], &mp->v3OneRightFromCenter_NC[2]);
string sNormal = pElem->Attribute( "Normal_NC" );
sscanf( sNormal.c_str(), "%lf %lf %lf", &mp->v3Normal_NC[0], &mp->v3Normal_NC[1], &mp->v3Normal_NC[2]);
string sPixDown = pElem->Attribute( "PixelDown_W" );
sscanf( sPixDown.c_str(), "%lf %lf %lf", &mp->v3PixelDown_W[0], &mp->v3PixelDown_W[1], &mp->v3PixelDown_W[2]);
string sPixRight = pElem->Attribute( "PixelRight_W" );
sscanf( sPixRight.c_str(), "%lf %lf %lf", &mp->v3PixelRight_W[0], &mp->v3PixelRight_W[1], &mp->v3PixelRight_W[2]);
//////////// cross ref data - as all keyframes are loaded we can cross ref with them.
//MapMakerData
{
std::vector<string> vsUids;
std::vector<int> vnUids;
KeyFrame * k = NULL;
std::vector<int>::iterator it;
int nSize = -1;
string sTmp;
TiXmlElement * pElem = hMP.FirstChild("MapMakerData").FirstChild("MeasurementKFs").ToElement();
if( pElem == NULL ) {
return false;
}
pElem->QueryIntAttribute( "size", &nSize );
const char * c = pElem->GetText();
if(c != NULL ) {
sTmp = c;
}
else {
sTmp = "";
}
vsUids = ChopAndUnquoteString(sTmp);
for(size_t i = 0; i < vsUids.size(); i++)
{
int *pN = ParseAndAllocate<int>(vsUids[i]);
if( pN )
{
vnUids.push_back( *pN );
delete pN;
}
}
if( (int)vnUids.size() != nSize ) {
cerr << "Warning: MapMakerData:MeasurementKFs size mismatch for map point "
<< uid << " : " << vnUids.size() << " != " << nSize << endl;
}
mp->pMMData = new MapMakerData();
for( it = vnUids.begin(); it != vnUids.end(); it++ )
{
k = _LookupKeyFrame( (*it) );
if( k != NULL ) {
mp->pMMData->sMeasurementKFs.insert( k );
}
else {
cerr << "Warning: keyframe " << (*it) << " not found for MapMakerData:MeasurementKFs cross ref" << endl;
}
}
vnUids.clear();
vsUids.clear();
pElem = hMP.FirstChild("MapMakerData").FirstChild("sNeverRetryKFs").ToElement();
if( pElem == NULL ) {
return false;
}
pElem->QueryIntAttribute( "size", &nSize );
c = pElem->GetText();
if(c != NULL ) {
sTmp = c;
}
else {
sTmp = "";
}
vsUids = ChopAndUnquoteString(sTmp);
for(size_t i = 0; i < vsUids.size(); i++)
{
int *pN = ParseAndAllocate<int>(vsUids[i]);
if( pN )
{
vnUids.push_back( *pN );
delete pN;
}
}
if( (int)vnUids.size() != nSize ) {
cerr << "Warning: MapMakerData:sNeverRetryKFs size mismatch for map point " << uid << endl;
}
for( it = vnUids.begin(); it != vnUids.end(); it++ )
{
k = _LookupKeyFrame( (*it) );
if( k != NULL ) {
mp->pMMData->sNeverRetryKFs.insert( k );
}
else {
cerr << "Warning: keyframe " << (*it) << " not found for MapMakerData:sNeverRetryKFs cross ref" << endl;
}
}
vnUids.clear();
vsUids.clear();
mmMapPointLoadLUT[ uid ] = mp;
if( bQueuePoint ) {
mpMap->qNewQueue.push_back( mp );
}
else {
// mp->RefreshPixelVectors();
mpMap->vpPoints.push_back( mp );
}
}
return true;
}
/**
* Load a list of mappoints recursivly
* @param hRoot XML node
* @return success
*/
bool MapSerializer::_LoadMapPoints( TiXmlHandle &hRoot )
{
{
int nSize = -1;
TiXmlHandle pNode = hRoot.FirstChild( "MapPoints" );
pNode.ToElement()->QueryIntAttribute("size", &nSize);
for(TiXmlElement* pElem = pNode.FirstChild().Element();
pElem != NULL;
pElem = pElem->NextSiblingElement() )
{
TiXmlHandle hmp( pElem );
if( !_LoadAMapPoint( hmp ) ) {
cerr << "Failed to Load point " << pElem->Attribute("id") << ". Abort." << endl;
return false;
}
}
if( (int)mpMap->vpPoints.size() != nSize ) {
cerr << "Loaded the wrong number of mappoints. " << mpMap->vpPoints.size()
<< " instead of " << nSize << ". Aborting" << endl;
return false;
}
}
//////////// load the new pending map points ////////////
{
int nSize = -1;
TiXmlHandle pNode = hRoot.FirstChild( "NewMapPoints" );
pNode.ToElement()->QueryIntAttribute("size", &nSize);
for(TiXmlElement* pElem = pNode.FirstChild().Element();
pElem != NULL;
pElem = pElem->NextSiblingElement() )
{
TiXmlHandle hmp( pElem );
if( !_LoadAMapPoint( hmp, true ) ) {
cerr << "Failed to Load queue point " << pElem->Attribute("id") << ". Abort." << endl;
return false;
}
}
if( (int)mpMap->qNewQueue.size() != nSize ) {
cerr << "Loaded the wrong number of new mappoints. " << mpMap->qNewQueue.size()
<< " instead of " << nSize << ". Aborting" << endl;
return false;
}
}
return true;
}
/**
* save the map class
* @param sPath the root folder path for the map
* @return status
*/
MapSerializer::MapStatus MapSerializer::_SaveMap( std::string sPath )
{
//////////// Get map lock ////////////
if( !_LockMap() ) {
cerr << "Failed to get map lock" << endl;
return MAP_FAILED;
}
TiXmlDocument xmlDoc; //XML file
string sMapFileName = sPath + "/map.xml";
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
xmlDoc.LinkEndChild( decl );
TiXmlElement * rootNode = new TiXmlElement(MAP_XML_ID);
xmlDoc.LinkEndChild( rootNode );
rootNode->SetAttribute("version", MAP_VERSION);
//////////// save the keyframes and map points ////////////
bool bOK = false;
_CreateSaveLUTs(); // create lookup tables for the mappoints and keyframes
bOK = _SaveKeyFrames( sPath, rootNode ); // recursively save each keyframe
if( !bOK ) {
_UnlockMap();
return MAP_FAILED;
}
bOK = _SaveMapPoints( rootNode ); // recursively save each map point
if( !bOK ) {
_UnlockMap();
return MAP_FAILED;
}
//////////// save the uids for the keyframes and map points in the failure queue ////////////
{
TiXmlElement * failElem = new TiXmlElement( "FailureQueue" );
rootNode->LinkEndChild( failElem );
failElem->SetAttribute( "size", mpMap->vFailureQueue.size() );
int k = -1, m = -1;
vector<std::pair<KeyFrame*, MapPoint*> >::iterator fq;
for( fq = mpMap->vFailureQueue.begin(); fq != mpMap->vFailureQueue.end(); fq++ )
{
k = _LookupKeyFrame( (*fq).first );
m = _LookupMapPoint( (*fq).second );
if( m != -1 && k != -1 ) {
TiXmlElement * kmElem = new TiXmlElement( "Failure" );
failElem->LinkEndChild( kmElem );
kmElem->SetAttribute( "kf", k );
kmElem->SetAttribute( "mp", m );
}
}
}
//////////// save the game data ////////////
TiXmlElement * game = new TiXmlElement( "Game" );
rootNode->LinkEndChild( game );
if( mpMap->pGame )
{
game->SetAttribute("type", mpMap->pGame->Name() );
string sFile = mpMap->pGame->Save( sPath );
if( !sFile.empty() ) {
game->SetAttribute("path", sFile );
}
}
else {
game->SetAttribute("type", "None");
}
//////////// relase map lock ////////////
_UnlockMap();
xmlDoc.SaveFile(sMapFileName);
return MAP_OK;
}
/**
* create a look up table for all the pointers to keyframes and map points
*/
void MapSerializer::_CreateSaveLUTs()
{
mmKeyFrameSaveLUT.clear();
mmMapPointSaveLUT.clear();
for( size_t i = 0; i < mpMap->vpKeyFrames.size(); i++ ) {
mmKeyFrameSaveLUT[ mpMap->vpKeyFrames[i] ] = i;
}
int nSize = mpMap->vpKeyFrames.size();
for( size_t i = 0; i < mpMap->vpKeyFrameQueue.size(); i++ ) {
mmKeyFrameSaveLUT[ mpMap->vpKeyFrames[i] ] = nSize + i;
}
for( size_t i = 0; i < mpMap->vpPoints.size(); i++ ) {
mmMapPointSaveLUT[ mpMap->vpPoints[i] ] = i;
}
nSize = mpMap->vpPoints.size();
for( size_t i = 0; i < mpMap->qNewQueue.size(); i++ ) {
mmMapPointSaveLUT[ mpMap->qNewQueue[i] ] = nSize + i;
}
}
/**
* Find a keyframe in the save lookup table and return its uid.
* -1 if it does not exist
* @param k the keyframe to find
* @return the UID
*/
int MapSerializer::_LookupKeyFrame( KeyFrame * k )
{
map< const KeyFrame *, int >::iterator i;
i = mmKeyFrameSaveLUT.find( k );
if( i != mmKeyFrameSaveLUT.end() ) {
return (*i).second;
}
else {
return -1;
}
}
/**
* find a map point in the save lookup table and return its uid. -1 if it does not exist
* @param m the map point to find
* @return the UID
*/
int MapSerializer::_LookupMapPoint( MapPoint * m )
{
map< const MapPoint *, int >::iterator i;
i = mmMapPointSaveLUT.find( m );
if( i != mmMapPointSaveLUT.end() ) {
return (*i).second;
}
else {
return -1;
}
}
/**
* Find a keyframe uid in the loading lookup table and return pointer to it.
* Null if it does not exist
* @param uid the keyframe to find
* @return pointer
*/
KeyFrame * MapSerializer::_LookupKeyFrame( int uid )
{
map< int, KeyFrame * >::iterator i;
i = mmKeyFrameLoadLUT.find( uid );
if( i != mmKeyFrameLoadLUT.end() ) {
return (*i).second;
}
else {
return NULL;
}
}
/**
* Find a map point uid in the loading lookup table and return pointer to it.
* Null if it does not exist
* @param uid the map point to find
* @return pointer
*/