-
Notifications
You must be signed in to change notification settings - Fork 12
/
MapLoader.cc
1471 lines (1237 loc) · 57.3 KB
/
MapLoader.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
/*
Copyright (C) 2005, ActivMedia Robotics, LLC
Copyright (C) 2006-2010 MobileRobots, Inc.
Copyright (C) 2011-2015 Adept Technology Inc.
Copyright (C) 2016-2017 Omron Adept Technologies
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* TODO add map loading into a new "World" interface ? */
// enable debug log messages:
//#define DEBUG 1
// to maybe get extensions like sincos():
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#ifndef __USE_GNU
#define __USE_GNU 1
#endif
#include <math.h>
#include <assert.h>
#include "stage.h"
#include "MapLoader.hh"
#include "RobotInterface.hh"
#include "ArMap.h"
#include "ariaUtil.h"
const double MapLoader::ReflectorThickness = 0.0200; // meters (=2cm).
#define PRINT_NUM_POINTS_CREATED 1
#define PRINT_NUM_LINES_CREATED 1
MapLoader::~MapLoader()
{
if(map && created_map)
delete map;
}
void MapLoader::cancelLoad() {
reset();
}
void MapLoader::addCallback(MapLoadedCallback cb)
{
//ArLog::log(ArLog::Normal, "MapLoader::addCallback(): adding callback: %p", (void*)cb);
callbacks.insert(cb);
//ArLog::log(ArLog::Normal, "MapLoader::addCallback(): current callbacks:");
//for (std::set<MapLoadedCallback>::iterator cb_it = callbacks.begin(); cb_it != callbacks.end(); ++cb_it)
// ArLog::log(ArLog::Normal, "\t\t%p", *cb_it);
}
void MapLoader::removeCallback(MapLoadedCallback cb)
{
//ArLog::log(ArLog::Normal, "MapLoader::removeCallback(): removing callback: %p", (void*)cb);
callbacks.erase(cb);
//ArLog::log(ArLog::Normal, "MapLoader::addCallback(): current callbacks:");
//for (std::set<MapLoadedCallback>::iterator cb_it = callbacks.begin(); cb_it != callbacks.end(); ++cb_it)
// ArLog::log(ArLog::Normal, "\t\t%p", *cb_it);
}
bool MapLoader::newMap(const std::string& newmapfile, RobotInterface *requestor, MapLoadedCallback cb, std::string *errorMsg)
{
#ifdef DEBUG
ArLog::log(ArLog::Normal, "MapLoader::newMap: newmapfile=%s", newmapfile.c_str());
#endif
if(!shouldReloadMap(newmapfile)) // If the robot has requested to change to the current map...
{
//if(requestor) requestor->warn("Not reloading map file \"%s\', it has not changed since last load.", newmapfile.c_str());
//else print_warning("Not reloading map file \"%s\', it has not changed since last load.", newmapfile.c_str());
if(myProcessState == NEWMAP_INACTIVE) // If the current map has already been processed...
{
//ArLog::log(ArLog::Normal, "MapLoader::newMap(): !shouldReloadMap: myProcessState == NEWMAP_INACTIVE: invoking the requesting robot's callback: %p", (void*)cb);
invokeMapLoadedCallback(cb, false, newmapfile, NULL); // ... tell the robot the map is loaded, and let its EmulatePioneer load the new map data
}
//else
//{
//ArLog::log(ArLog::Normal, "MapLoader::newMap(): !shouldReloadMap: myProcessState != NEWMAP_INACTIVE: not invoking the requesting robot's callback");
//}
return true;
}
/// ??? @todo ? Get points and lines change timestamps from ArMap and check against saved times.
/// (Though note that this will create a bug, that modifying reflectors or ?
//obstacle cairns will be ignored)
//if (requestor) ArLog::log(ArLog::Normal, "MapLoader::newMap(str, RI, MLCb, str) %s actually loading new map: %s", requestor->getRobotName().c_str(), newmapfile.c_str());
//else ArLog::log(ArLog::Normal, "MapLoader::newMap(str, RI, MLCb, str) actually loading new map: %s", newmapfile.c_str());
reset();
ArTime timer;
if(!map) {
map = new ArMap();
created_map = true;
}
char errbuf[128];
struct stat path_st = {0};
struct stat file_st = {0};
char fileName[256];
char curPath[256];
char copyPath[256];
strcpy(curPath, newmapfile.c_str());
ArUtil::getDirectory(newmapfile.c_str(), curPath, 256);
strcpy(copyPath, curPath);
if(hostHasEM)
strcat(copyPath, "./sim/");
else
strcat(copyPath, "/copyMap/");
if(stat(newmapfile.c_str(), &file_st) == -1 || stat(copyPath, &path_st) == -1)
{
stg_print_msg("Could either not find the map or not find the copyDir. Processing in-place.");
if(!map->readFile(newmapfile.c_str(), errbuf, 127))
{
if(errorMsg) *errorMsg = errbuf;
return false;
}
//print_debug("Took %d msec to read map file", timer.mSecSince());
//ArLog::log(ArLog::Normal, "MapLoader::newMap(str, RI, MLCb, str): using requestor (%p) and sending cb (%p) to mapLoader.newMap(MLCb)", (void*)requestor, (void*)cb);
return newMap(cb);
}
else
{
stg_print_msg("Found the map and the copyDir. Copying to new location: %s", copyPath);
char cpCommand[256];
sprintf(cpCommand, "cp \"%s\" \"%s\"", newmapfile.c_str(), copyPath);
stg_print_msg("Copy command: %s", cpCommand);
system(cpCommand);
ArUtil::getFileName(newmapfile.c_str(), fileName, 256);
std::string newname;
newname.clear();
newname += copyPath;
newname += fileName;
stg_print_msg("Resetting the newname: %s", newname.c_str());
if(!map->readFile(newname.c_str(), errbuf, 127))
{
stg_print_msg("Failed to read map file: %s", newname.c_str());
if(errorMsg) *errorMsg = errbuf;
return false;
}
//print_debug("Took %d msec to read map file", timer.mSecSince());
//ArLog::log(ArLog::Normal, "MapLoader::newMap(str, RI, MLCb, str): using requestor (%p) and sending cb (%p) to mapLoader.newMap(MLCb)", (void*)requestor, (void*)cb);
return newMap(cb);
}
}
bool MapLoader::newMap(ArMap *newmap, MapLoadedCallback cb)
{
//ArLog::log(ArLog::Normal, "MapLoader::newMap(ArMap, MLCb) enter");
reset();
map = newmap;
return newMap(cb);
}
bool MapLoader::newMap(MapLoadedCallback cb)
{
#ifdef DEBUG
ArLog::log(ArLog::Normal, "MapLoader::newMap(MLCb): cb: %p", (void*)cb);
//ArLog::log(ArLog::Normal, "MapLoader::newMap(MLCb): map: %p", (void*)map);
#endif
// Prepare class member variables for use from MapLoader::process()
//callback = cb; // obsolete // TODO: remove cb from all function argument lists
mapfile = map->getFileName();
myLoadedData = false;
myProcessState = MapLoader::NEWMAP_STARTPROCESS;
loading = true;
// TODO build a new matrix at the right resolution and size and use it to
// filter out redundant points for that resolution (avoid too much data in
// stg_point_t array for instance) as we get
// data from ArMap, then add robots from old matrix, then swap in new
// matrix. This should be doable over several process() calls, and avoid
// having to resize the world.
return true;
}
#ifdef DEBUG
#define DEBUG_LOG_NEW_STATE() print_debug("MapLoader::process(): Set new state, is now %s (%d)", stateName(myProcessState), myProcessState);
#define DEBUG_LOG_STATE_ACTION() print_debug("MapLoader::process(): Doing %s (%d)...", stateName(myProcessState), myProcessState);
#else
#define DEBUG_LOG_NEW_STATE() {}
#define DEBUG_LOG_STATE_ACTION() {}
#endif
bool MapLoader::process(unsigned int maxTime)
{
#define SINGLE_PROCESS_LINE 1 // if this is '1', the loop will check remeaining time before processing each entry in map->getLines(). else, it will process them all at once
#define SINGLE_PROCESS_POINT 1 // if this is '1', the loop will check remeaining time before processing each entry in map->getPoints(). else, it will process them all at once
#define SINGLE_PROCESS_CUSTTYPE 1 // if this is '1', the loop will check remeaining time before processing each entry in map->getMapInfo(). else, it will process them all at once
#define SINGLE_PROCESS_CAIRNOBJ 1 // if this is '1', the loop will check remeaining time before processing each entry in map->getMapObjects(). else, it will process them all at once
#ifdef DEBUG
print_debug("MapLoader::process() called (maxTime=%u). State is %s (%d). SINGLE_PROCESS_LINE? %d SINGLE_PROCESS_POINT? %d SINGLE_PROCESS_CUSTTYPE? %d SINGLE_PROCESS_CAIRNOBJ? %d", maxTime, stateName(myProcessState), myProcessState, SINGLE_PROCESS_LINE, SINGLE_PROCESS_POINT, SINGLE_PROCESS_CUSTTYPE, SINGLE_PROCESS_CAIRNOBJ);
#endif
// There is no pending newMap processing to service
if (myProcessState == MapLoader::NEWMAP_INACTIVE)
{
return true;
}
// There's no time to process
if (maxTime == 0)
return true;
// There is no map object
#ifdef DEBUG
ArLog::log(ArLog::Normal, "MapLoader::process(): map: %p", (void*)map);
#endif
if (map == NULL)
return false;
// This is a dummy state that performs no action, and returns to the main loop.
// This is necessary because the map change procedure is called asynchronously
// and calls ArMap::readFile(), blocking other things and taking up lots of time.
// After this happens, we want to return to the main loop processes before beginning
// work here.
if (myProcessState == MapLoader::NEWMAP_STARTPROCESS)
{
myProcessState = MapLoader::NEWMAP_LOADLINESTART;
DEBUG_LOG_NEW_STATE();
return true;
}
ArTime mapProcessStart;
// Load the lines from the new map file
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_LOADLINESTART))
return true;
if (myProcessState == MapLoader::NEWMAP_LOADLINESTART)
{
DEBUG_LOG_STATE_ACTION();
//NewMapLoadTime.setToNow();
myNumLines = map->getLines()->size();
if (myNumLines > 0)
{
//myPolysPerChunk = 10000; // TODO: Hardcoded for now. Create MobileSim commandline parameter to overwrite this value
myNumMapPolysChunks = myNumLines / myPolysPerChunk;
if (myNumLines % myPolysPerChunk != 0) ++myNumMapPolysChunks;
myMapPolysChunks.clear();
myMapPolysChunks.resize(myNumMapPolysChunks);
for (int i = 0; i < myNumMapPolysChunks; ++i)
{
if(i < myNumMapPolysChunks-1 || myNumLines % myPolysPerChunk == 0)
myMapPolysChunks[i] = stg_polygons_create(myPolysPerChunk);
else
myMapPolysChunks[i] = stg_polygons_create(myNumLines % myPolysPerChunk);
}
myLine_it = map->getLines()->begin();
myNumPolys = 0;
myProcessState = MapLoader::NEWMAP_LOADLINECONT;
DEBUG_LOG_NEW_STATE()
}
else
{
myNumMapPolysChunks = 0;
// If there are no lines to process, just skip to the next state
myProcessState = MapLoader::NEWMAP_LOADPOINTSTART;
DEBUG_LOG_NEW_STATE()
}
ArLog::log(ArLog::Normal, "MapLoader::process(): myNumLines: %lu, myPolysPerChunk: %lu, myNumMapPolysChunks: %lu", myNumLines, myPolysPerChunk, myNumMapPolysChunks);
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_LOADLINESTART section finished at %d msec.", NewMapLoadTime.mSecSince());
}
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_LOADLINECONT))
return true;
if (myProcessState == MapLoader::NEWMAP_LOADLINECONT)
{
DEBUG_LOG_STATE_ACTION();
ArTime timer;
if(myNumLines == 0)
{
myProcessState = MapLoader::NEWMAP_LOADPOINTSTART;
DEBUG_LOG_NEW_STATE()
myLoadedData = true;
return true;
}
for(; myLine_it != map->getLines()->end(); ++myLine_it)
{
#if SINGLE_PROCESS_LINE
// Make sure we have time left for one more iteration
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_LOADLINECONT))
{
//ArLog::log(ArLog::Normal, "MobileSim map loader: exiting this process loop at %lu lines...", myNumPolys);
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_LOADLINECONT section took %d msec.", timer.mSecSince());
return true;
}
#endif
size_t curPolysChunkIdx = (myNumPolys / myPolysPerChunk);
stg_polygon_t* curPolysChunk = myMapPolysChunks[curPolysChunkIdx];
size_t curPolysSubIdx = (myNumPolys % myPolysPerChunk);
// record this line. convert mm to m
stg_point_t v1 = {(*myLine_it).getX1() / 1000.0, (*myLine_it).getY1() / 1000.0};
stg_point_t v2 = {(*myLine_it).getX2() / 1000.0, (*myLine_it).getY2() / 1000.0};
stg_polygon_append_points(&curPolysChunk[curPolysSubIdx], &v1, 1);
stg_polygon_append_points(&curPolysChunk[curPolysSubIdx], &v2, 1);
#if PRINT_NUM_LINES_CREATED
if(myNumPolys % myPolysPerChunk == 0)
ArLog::log(ArLog::Normal, "MobileSim map loader: At %lu lines...", myNumPolys);
#endif
++myNumPolys;
}
// If the process has reached the end of the list, move on to the next state
myLoadedData = true;
myProcessState = MapLoader::NEWMAP_LOADPOINTSTART;
DEBUG_LOG_NEW_STATE()
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_LOADLINECONT section finished at %d msec.", NewMapLoadTime.mSecSince());
}
// Load the points from the new map file
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_LOADPOINTSTART))
return true;
if (myProcessState == MapLoader::NEWMAP_LOADPOINTSTART)
{
DEBUG_LOG_STATE_ACTION();
myNumPoints = map->getPoints()->size();
if(myNumPoints > 0)
{
//myPointsPerChunk = 100000; // TODO: Hardcoded for now. Create MobileSim commandline parameter to overwrite this value
myNumMapPointsChunks = myNumPoints / myPointsPerChunk;
if (myNumPoints % myPointsPerChunk != 0) ++myNumMapPointsChunks;
myMapPointsChunks.clear();
myMapPointsChunks.resize(myNumMapPointsChunks);
for (int i = 0; i < myNumMapPointsChunks; ++i)
{
#ifdef DEBUG
print_debug("MapLoader::process(): Allocating chunk %d of %d...", i, myNumMapPointsChunks);
#endif
if(i < myNumMapPointsChunks-1 || myNumPoints % myPointsPerChunk == 0)
{
#ifdef DEBUG
print_debug("MapLoader::process(): stg_points_create(myPolysPerChunk %d)...", myPolysPerChunk);
#endif
myMapPointsChunks[i] = stg_points_create(myPolysPerChunk);
}
else
{
#ifdef DEBUG
print_debug("MapLoader::process(): stg_points_create(myNumPoints %d %% myPointsPerChunk %d == %d)", myNumPoints, myPointsPerChunk, myNumPoints % myPointsPerChunk);
#endif
//myMapPointsChunks[i] = stg_points_create(myNumLines % myPointsPerChunk);
myMapPointsChunks[i] = stg_points_create(myNumPoints % myPointsPerChunk);
}
}
myPoint_it = map->getPoints()->begin();
myPointCount = 0;
myProcessState = MapLoader::NEWMAP_LOADPOINTCONT;
DEBUG_LOG_NEW_STATE()
}
else
{
myNumMapPointsChunks = 0;
// If there are no points to process, just skip to the next state
myProcessState = MapLoader::NEWMAP_LOADCHECK;
DEBUG_LOG_NEW_STATE()
}
ArLog::log(ArLog::Normal, "MapLoader::process(): myNumPoints: %lu, myPointsPerChunk: %lu, myNumMapPointsChunks: %lu", myNumPoints, myPointsPerChunk, myNumMapPointsChunks);
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_LOADPOINTSTART section finished at %d msec.", NewMapLoadTime.mSecSince());
}
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_LOADPOINTCONT))
return true;
if (myProcessState == MapLoader::NEWMAP_LOADPOINTCONT)
{
DEBUG_LOG_STATE_ACTION();
if(myNumLines == 0)
{
myProcessState = MapLoader::NEWMAP_LOADCHECK;
DEBUG_LOG_NEW_STATE()
myLoadedData = true;
return true;
}
for(; myPoint_it != map->getPoints()->end(); ++myPoint_it)
{
#if SINGLE_PROCESS_POINT
// Make sure we have time left for one more iteration
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_LOADPOINTCONT))
return true;
#endif
size_t curPointsChunkIdx = (myPointCount / myPointsPerChunk);
stg_point_t* curPointsChunk = myMapPointsChunks[curPointsChunkIdx];
size_t curPointsSubIdx = (myPointCount % myPointsPerChunk);
curPointsChunk[curPointsSubIdx].x = (stg_meters_t) ( myPoint_it->getX() / 1000.0 ); // convert mm to m
curPointsChunk[curPointsSubIdx].y = (stg_meters_t) ( myPoint_it->getY() / 1000.0 );
#if PRINT_NUM_POINTS_CREATED
if(myPointCount % myPointsPerChunk == 0)
ArLog::log(ArLog::Normal, "MobileSim map loader: At %lu points...", myPointCount);
#endif
++myPointCount;
}
// If the process has reached the end of the list, move on to the next state
myLoadedData = true;
myProcessState = MapLoader::NEWMAP_LOADCHECK;
DEBUG_LOG_NEW_STATE()
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_LOADPOINTCONT section finished at %d msec.", NewMapLoadTime.mSecSince());
}
// Check to make sure something has been loaded from the new map file
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_LOADCHECK))
return true;
if (myProcessState == MapLoader::NEWMAP_LOADCHECK)
{
DEBUG_LOG_STATE_ACTION();
if(!myLoadedData)
{
stg_print_warning("MobileSim: No obstacle data loaded from map file \"%s\"!", mapfile.c_str());
//if(!loadPoints) stg_print_warning("MobileSim: Requested not to load point data, try enabling.");
//if(!loadLines) stg_print_warning("MobileSim: Requested not to load line data, try enabling.");
}
// Load origin georeference
haveMapOriginLLA = map->hasOriginLatLongAlt();
if(haveMapOriginLLA)
{
mapOriginLLA.setX(map->getOriginLatLong().getX());
mapOriginLLA.setY(map->getOriginLatLong().getY());
mapOriginLLA.setZ(map->getOriginAltitude());
stg_print_msg("MobileSim: Map has OriginLatLon point, will be able to send simulated GPS coordinates if requested.");
}
myProcessState = MapLoader::NEWMAP_STAGECREATE;
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_LOADCHECK section finished at %d msec.", NewMapLoadTime.mSecSince());
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_LOAD* sections took %d msec.", NewMapLoadTime.mSecSince());
}
// Create the Stage model from themap file (TODO: probably safe to move NEWMAP_STAGECLEAR below this, in pursuit of making NEWMAP_STAGECLEAR/NEWMAP_STAGEINSERT atomic)
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_STAGECREATE))
return true;
if (myProcessState == MapLoader::NEWMAP_STAGECREATE)
{
DEBUG_LOG_STATE_ACTION();
//NewMapStageTime.setToNow();
// find a unique id number
stg_id_t id = 0;
for(id = 0; stg_world_get_model(world, id) != NULL && id <= STG_ID_T_MAX; ++id)
;
if(id == STG_ID_T_MAX)
{
stg_print_error("MobileSim: !!! too many models in the world, can't create a new one.");
return false;
}
// create model TODO use stg_world_new_model instead?
// set as a background figure, so it isn't redrawn every time the robot moves
// or whatever.
myMapModel = stg_model_create(world, NULL, id, mapfile.c_str(), "model", "model", 0, NULL, TRUE);
myModelsToInit.push_back(myMapModel);
myMapPolysModels.clear();
myMapPolysModels.resize(myNumMapPolysChunks);
for(int i = 0; i < myNumMapPolysChunks; ++i)
{
myMapPolysModels[i] = stg_model_create(world, NULL, id, mapfile.c_str(), "model", "model", 0, NULL, TRUE);
myModelsToInit.push_back(myMapPolysModels[i]);
}
myCurPolysChunkIdx = 0; // This prepares NEWMAP_STAGEINITPOLY to start at the first polys chunk
myMapPointsModels.clear();
myMapPointsModels.resize(myNumMapPointsChunks);
for(int i = 0; i < myNumMapPointsChunks; ++i)
{
myMapPointsModels[i] = stg_model_create(world, NULL, id, mapfile.c_str(), "model", "model", 0, NULL, TRUE);
myModelsToInit.push_back(myMapPointsModels[i]);
}
myCurPointsChunkIdx = 0; // This prepares NEWMAP_STAGEINITPOLY to start at the first points chunk
// get the color
stg_color_t mapcolor = stg_lookup_color("dark gray");
if(mapcolor == 0xFF0000) mapcolor = 0; // black if not found
// get size
double maxX_mm = 0;
double minX_mm = 0;
double maxY_mm = 0;
double minY_mm = 0;
if(myNumPoints > 0 && myNumLines > 0)
{
maxX_mm = fmax(map->getLineMaxPose().getX(), map->getMaxPose().getX());
minX_mm = fmin(map->getLineMinPose().getX(), map->getMinPose().getX());
maxY_mm = fmax(map->getLineMaxPose().getY(), map->getMaxPose().getY());
minY_mm = fmin(map->getLineMinPose().getY(), map->getMinPose().getY());
}
else if(myNumPoints > 0)
{
maxX_mm = map->getMaxPose().getX();
minX_mm = map->getMinPose().getX();
maxY_mm = map->getMaxPose().getY();
minY_mm = map->getMinPose().getY();
}
else if(myNumLines > 0)
{
maxX_mm = map->getLineMaxPose().getX();
minX_mm = map->getLineMinPose().getX();
maxY_mm = map->getLineMaxPose().getY();
minY_mm = map->getLineMinPose().getY();
}
stg_size_t size;
size.x = maxX_mm/1000.0 - minX_mm/1000.0; //mm to m
size.y = maxY_mm/1000.0 - minY_mm/1000.0; //mm to m
stg_print_msg("New world from loading map \"%s\" will be %f x %f meters in size.", mapfile.c_str(), size.x, size.y);
// get origin offset (obsolete?)
//stg_pose_t offset;
//offset.x = (size.x / 2.0) + (minX_mm / 1000.0);
//offset.y = (size.y / 2.0) + (minY_mm / 1000.0);
//offset.a = 0;
int grid = 0; // Turn off grid
int movemask = 0; // Make it unmovable
time_t tm = time(NULL);// store creation time and file source
// Give the basic map initialization to each model
int model_num = 0;
for (std::list<stg_model_t*>::iterator mod_it = myModelsToInit.begin(); mod_it != myModelsToInit.end(); ++mod_it)
{
#ifdef DEBUG
ArLog::log(ArLog::Normal, "Initializing model_num: %d", model_num);
#endif
++model_num;
stg_model_t *cur_mod = (*mod_it);
#ifdef DEBUG
ArLog::log(ArLog::Normal, "THIS IS THE POINTER: %u", cur_mod);
#endif
// store the map file name
stg_model_set_property(cur_mod, "source", (void*)mapfile.c_str(), mapfile.size()+1);
// set color
stg_model_set_property(cur_mod, "color", &mapcolor, sizeof(mapcolor));
// set size
stg_model_set_size(cur_mod, size);
// but don't scale it to that size, lines and points are already at the right
// places for correct scale
stg_model_set_scaling(cur_mod, FALSE);
// set origin offset (obsolete?)
//stg_model_set_origin(cur_mod, offset);
stg_model_set_property(cur_mod, "grid", &grid, sizeof(int));
stg_model_set_property(cur_mod, "mask", &movemask, sizeof(int));
//stg_model_set_property(cur_mod, "source", (void*)mapfile.c_str(), mapfile.size()+1); // redundant
stg_model_set_property(cur_mod, "creation_time", &tm, sizeof(tm));
}
myProcessState = MapLoader::NEWMAP_STAGEINITPOLY;
DEBUG_LOG_NEW_STATE()
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_STAGECREATE section finished at %d msec.", NewMapLoadTime.mSecSince());
}
// Insert polys into the Stage world (TODO: probably safe to move NEWMAP_STAGECLEAR below this, in pursuit of making NEWMAP_STAGECLEAR/NEWMAP_STAGEINSERT atomic)
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_STAGEINITPOLY))
return true;
if (myProcessState == MapLoader::NEWMAP_STAGEINITPOLY)
{
DEBUG_LOG_STATE_ACTION();
#ifdef DEBUG
ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_STAGEINITPOLY: myNumMapPolysChunks: %lu", myNumMapPolysChunks);
#endif
ArTime timer;
if(myNumMapPolysChunks > 0)
{
timer.setToNow();
//ArLog::log(ArLog::Normal, "MapLoader::process(): calling stg_model_set_polygons(): myNumPolys: %lu", myNumPolys);
stg_model_t *curPolysModel = myMapPolysModels[myCurPolysChunkIdx];
stg_polygon_t *curPolysChunk = myMapPolysChunks[myCurPolysChunkIdx];
if(myCurPolysChunkIdx < myNumMapPolysChunks-1 || myNumLines % myPolysPerChunk == 0)
{
#ifdef DEBUG
ArLog::log(ArLog::Normal, "MapLoader::process(): setting polygons for chunk %d, containing %lu polys", myCurPolysChunkIdx, myPolysPerChunk);
#endif
stg_model_set_polygons(curPolysModel, curPolysChunk, myPolysPerChunk);
}
else
{
#ifdef DEBUG
ArLog::log(ArLog::Normal, "MappLoader::process(): setting polygons for chunk %d, containing %lu polys", myCurPolysChunkIdx, myNumLines % myPolysPerChunk);
#endif
stg_model_set_polygons(curPolysModel, curPolysChunk, myNumLines % myPolysPerChunk);
}
#ifdef DEBUG
print_debug("Took %d msec to store model polygons in myMapPolysModel.", timer.mSecSince());
#endif
// TODO: Why is this call free(myMapPolys), while the call below is stg_points_destroy(myMapPoints) ?
free(curPolysChunk); // it was copied by stg_model_init_polygons
++myCurPolysChunkIdx;
}
//ArLog::log(ArLog::Normal, "MapLoader::process(): myCurPolysChunkIdx: %d, myNumMapPolysChunks: %lu", myCurPolysChunkIdx, myNumMapPolysChunks);
if(myCurPolysChunkIdx >= myNumMapPolysChunks)
{
//ArLog::log(ArLog::Normal, "Continuing to NEWMAP_STAGEINITPOINT");
myProcessState = MapLoader::NEWMAP_STAGEINITPOINT;
DEBUG_LOG_NEW_STATE()
}
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_STAGEINITPOLY section finished at %d msec.", NewMapStageTime.mSecSince());
}
// Insert polys into the Stage world
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_STAGEINITPOINT))
return true;
if (myProcessState == MapLoader::NEWMAP_STAGEINITPOINT)
{
DEBUG_LOG_STATE_ACTION();
#ifdef DEBUG
print_debug("MapLoader::process(): myNumMapPointsChunks: %lu", myNumMapPointsChunks);
#endif
ArTime timer;
if(myNumMapPointsChunks > 0)
{
timer.setToNow();
#ifdef DEBUG
print_debug("MapLoader::process(): calling stg_model_init_points(): myNumPolys: %lu", myNumPoints);
#endif
stg_model_t *curPointsModel = myMapPointsModels[myCurPointsChunkIdx];
stg_point_t *curPointsChunk = myMapPointsChunks[myCurPointsChunkIdx];
#ifdef DEBUG
print_debug("MapLoader::process(): calling stg_model_init_points(): myNumPolys: %lu", myNumPoints);
#endif
if(myCurPointsChunkIdx < myNumMapPointsChunks-1 || myNumPoints % myPointsPerChunk == 0)
{
#ifdef DEBUG
print_debug("MapLoader::process(): setting points for chunk %d, containing %lu points (from myPointsPerChunk)", myCurPointsChunkIdx, myPointsPerChunk);
#endif
stg_model_init_points(curPointsModel, curPointsChunk, myPointsPerChunk);
}
else
{
#ifdef DEBUG
print_debug("MapLoader::process(): setting points for chunk %d, containing %lu points (myNumPoints %d %% myPointsPerChunk %d)", myCurPointsChunkIdx, myNumPoints % myPointsPerChunk, myNumPoints, myPointsPerChunk);
#endif
stg_model_init_points(curPointsModel, curPointsChunk, myNumPoints % myPointsPerChunk);
}
//print_debug("Took %d msec to store model points in myMapPointsModel.", timer.mSecSince());
// TODO: Why is this call stg_points_destroy(myMapPoints), while the call above is free(myMapPolys) ?
stg_points_destroy(curPointsChunk); // it was copied by stg_model_init_points
++myCurPointsChunkIdx;
}
//ArLog::log(ArLog::Normal, "MapLoader::process(): myCurPointsChunkIdx: %d, myNumMapPointsChunks: %lu", myCurPointsChunkIdx, myNumMapPointsChunks);
if(myCurPointsChunkIdx >= myNumMapPointsChunks)
{
//ArLog::log(ArLog::Normal, "Continuing to NEWMAP_STAGECLEAR");
myProcessState = MapLoader::NEWMAP_STAGECLEAR;
DEBUG_LOG_NEW_STATE()
}
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_STAGEINITPOINT section finished at %d msec.", NewMapStageTime.mSecSince());
}
// Clear everything from the Stage world (leave this atomic unless absolutely necessary) // TODO: moving this downward toward NEWMAP_STAGEINSERT
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_STAGECLEAR))
return true;
if (myProcessState == MapLoader::NEWMAP_STAGECLEAR)
{
DEBUG_LOG_STATE_ACTION();
// Clear any existing map models
for(std::set<stg_model_t*>::const_iterator i = mapModels.begin(); i != mapModels.end(); i++)
{
assert(*i);
stg_world_remove_model(world, *i);
//printf("clearMap: destroying model \"%s\"...\n", stg_model_get_token(*i));
stg_model_destroy(*i);
}
mapModels.clear();
myProcessState = MapLoader::NEWMAP_STAGEINSERT;
DEBUG_LOG_NEW_STATE()
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_STAGECLEAR section finished at %d msec.", NewMapStageTime.mSecSince());
}
// Insert polys into the Stage world
//if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_STAGEINSERT)) // TODO: This check was removed to make the NEWMAP_STAGECLEAR/INSERT atomic. Pretty sure it won't cause problems, but leaving the line in case it needs to be reimplemented
// return true;
if (myProcessState == MapLoader::NEWMAP_STAGEINSERT)
{
DEBUG_LOG_STATE_ACTION();
// Remember the cairn objects model
mapModels.insert(myMapModel); // Still contains Cairn objects
// Remember the polygons models
for(int i = 0; i < myNumMapPolysChunks; ++i)
{
mapModels.insert(myMapPolysModels[i]); // Remember this model locally
stg_world_add_model(world, myMapPolysModels[i]); // Add model to stage world. Just an entry in the hash table.
}
// Remember the points models
for(int i = 0; i < myNumMapPointsChunks; ++i)
{
mapModels.insert(myMapPointsModels[i]); // Remember this model locally
stg_world_add_model(world, myMapPointsModels[i]); // Add model to stage world. Just an entry in the hash table.
}
myProcessState = MapLoader::NEWMAP_CUSTTYPESTART;
DEBUG_LOG_NEW_STATE();
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_STAGEINSERT section finished at %d msec.", NewMapStageTime.mSecSince());
//ArLog::log(ArLog::Normal, "MapLoader::process(): NEWMAP_STAGE* sections took %d msec.", NewMapLoadTime.mSecSince());
}
// Process the Custom type definitions
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_CUSTTYPESTART))
return true;
if (myProcessState == MapLoader::NEWMAP_CUSTTYPESTART)
{
DEBUG_LOG_STATE_ACTION();
// Check special simulator attributes of custom map object type definitions,
// and create models for objects as neccesary.
// TODO check Color0 and Color1, SonarReflect.
// Built in reflector type always has a high laser retun value by default
ObjectClass reflector_class("Reflector");
reflector_class.laser_return = 2;
myObjectClasses["Reflector"] = reflector_class;
myCusType_it = map->getMapInfo()->begin();
myProcessState = MapLoader::NEWMAP_CUSTTYPECONT;
DEBUG_LOG_NEW_STATE();
}
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_CUSTTYPECONT))
return true;
if (myProcessState == MapLoader::NEWMAP_CUSTTYPECONT)
{
DEBUG_LOG_STATE_ACTION();
for(; myCusType_it != map->getMapInfo()->end(); ++myCusType_it)
{
#if SINGLE_PROCESS_CUSTTYPE
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_CUSTTYPECONT))
return true;
#endif
const char *type_name = (*myCusType_it)->getArg(1);
if( strncmp(type_name, "Name=", 5) != 0 )
{
//stg_print_warning("MobileSim: First MapInfo attribute is not \"Name\", skipping.");
continue;
}
type_name += strlen("Name="); // skip past the "Name=" prefix
ObjectClass new_class(type_name);
const char *shape = (*myCusType_it)->getArg(0);
// XXX BoundaryType not implemented yet
if(strcmp(shape, "SectorType") != 0)
continue;
// Reflectors can be built-in reflectors, or have a name that
// previous versions of MobileSim interpreted as automatically being
// reflectors.
int val = 1;
const char* endTag = strrchr(type_name, '.');
if( strcmp( type_name, "Sim.Reflector") == 0
|| strcmp( type_name, "Reflector") == 0
|| (endTag && strcmp(endTag, ".Reflect") == 0)
)
{
new_class.laser_return = 2;
}
// Check remaining attributes for special simulator things
for(size_t a = 2; a < (*myCusType_it)->getArgc(); ++a)
{
char buf[256];
ArUtil::stripQuotes(buf, (*myCusType_it)->getArg(a), 256);
// Reflective to laser?
new_class.laser_return = 0;
if(strncmp(buf, "Sim.LaserReflect=", strlen("Sim.LaserReflect=")) == 0)
{
if(strncmp(buf, "Sim.LaserReflect=no", strlen("Sim.LaserReflect=no")) == 0 || strncmp(buf, "Sim.LaserReflect=false", strlen("Sim.LaserReflect=false")) == 0)
new_class.laser_return = 0;
else
new_class.laser_return = atoi( buf + strlen("Sim.LaserReflect=") ) + 1; // Need to add one because Stage starts highly reflective objects at 2, but SICK/Aria at 1
stg_print_msg("MobileSim: Will use reflection value %d for objects with type %s (from Sim.LaserReflect attribute in MapInfo)", new_class.laser_return, type_name);
}
// To sonar?
if(strncmp(buf, "Sim.SonarReflect=no", strlen("Sim.SonarReflect=no")) == 0 || strncmp(buf, "Sim.SonarReflect=false", strlen("Sim.SonarReflect=false")) == 0)
{
new_class.sonar_return = false;
stg_print_msg("MobileSim: Objects of type %s %s be visible to sonar (from Sim.SonarReflect attribute in MapInfo)", type_name, new_class.sonar_return?"will":"will not");
}
new_class.obstacle = false;
// Obstacle to robot?
if(strcasecmp(buf, "Sim.Obstacle=yes") == 0 || strcasecmp(buf, "Sim.Obstacle=true") == 0)
{
stg_print_msg("MobileSim: Objects of type %s will be represented as obstacles (from Sim.Obstacle attribute in MapInfo for %s)", type_name, type_name);
new_class.obstacle = true;
}
// Non-obstacle to robot?
if(strcasecmp(buf, "Sim.Obstacle=no") == 0 || strcasecmp(buf, "Sim.Obstacle=false") == 0)
{
stg_print_msg("MobileSim: Objects of type %s will be represented as non-obstacle objects (from Sim.Obstacle attribute in MapInfo for %s)", type_name, type_name);
new_class.obstacle = false;
}
}
myObjectClasses[type_name] = new_class;
}
// If the process has reached the end of the list, move on to the next state
myProcessState = MapLoader::NEWMAP_CAIRNSTART;
DEBUG_LOG_NEW_STATE();
}
// Process the Cairn objects
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_CAIRNSTART))
return true;
if (myProcessState == MapLoader::NEWMAP_CAIRNSTART)
{
DEBUG_LOG_STATE_ACTION();
myCairnObj_it = map->getMapObjects()->begin();
myProcessState = MapLoader::NEWMAP_CAIRNCONT;
DEBUG_LOG_NEW_STATE();
}
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_CAIRNCONT))
return true;
if (myProcessState == MapLoader::NEWMAP_CAIRNCONT)
{
DEBUG_LOG_STATE_ACTION();
// Create special objects for certain Cairn objects.
// Reflector: make a line in the map with bright reflectance.
// Sim.BoxObstacle: Make a box that the user can move.
for(; myCairnObj_it != map->getMapObjects()->end(); ++myCairnObj_it)
{
#if SINGLE_PROCESS_CAIRNOBJ
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_CAIRNCONT))
return true;
#endif
ArMapObject* obj = (*myCairnObj_it);
if(obj == NULL) continue;
stg_model_t* model = NULL;
bool builtinReflector = false;
// XXX this needs to be refactored a bit, probably eliminate the seperate
// loadReflector and LoadBoxObstacle functions, just set unique properties
// seperately.
std::map<std::string, ObjectClass>::iterator c = myObjectClasses.find(obj->getType());
if(c != myObjectClasses.end())
{
// Built-in Reflector objects have special fixed properties (color, shape, etc.)
if(strcmp(obj->getType(), "Reflector") == 0 || c->second.laser_return > 1)
{
builtinReflector = true;
model = loadReflector(obj, myMapModel, c->second.laser_return);
}
// Is the object of a type (class) that should be an obstacle?
else if (c->second.obstacle)
{
model = loadBoxObstacle(obj, myMapModel, c->second);
}
// Otherwise, ignore it.
}
// TODO support line-shaped obstacles, and reflective thngs that aren't also
// obstacles (they're phantom reflectors)
if(model == NULL) continue; // no simulator obstacle was created for this map object
// store file it was loaded from and current time
stg_model_set_property(model, "source", (void*)mapfile.c_str(), mapfile.size()+1);
time_t t = time(NULL);
stg_model_set_property(model, "creation_time", &t, sizeof(t));
mapModels.insert(model);
}
// If the process has reached the end of the list, move on to the next state
myProcessState = MapLoader::NEWMAP_RESIZE;
DEBUG_LOG_NEW_STATE();
}
// Process the resize
// Note: this portion will probably always blow the maxTime. The effect is that it will delay the clientOutput/stageUpdate
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_RESIZE))
return true;
if (myProcessState == MapLoader::NEWMAP_RESIZE)
{
DEBUG_LOG_STATE_ACTION();
// resize world
/// @todo Only resize if it got bigger. Also should optimize this, it takes forever.
stg_world_resize_to_contents(world, 10);
//stg_world_unlock(world);
myProcessState = MapLoader::NEWMAP_CALLBACK;
DEBUG_LOG_NEW_STATE();
}
// Process the callback
if (!processTimeCheck(maxTime, mapProcessStart, MapLoader::NEWMAP_CALLBACK))
return true;
if (myProcessState == MapLoader::NEWMAP_CALLBACK)
{
DEBUG_LOG_STATE_ACTION();
//if(callback)
// invokeMapLoadedCallback(callback, true, mapfile, map);
//ArLog::log(ArLog::Normal, "MapLoader::process(): invoking all mapLoaded callbacks");
if(!callbacks.empty())
{
for(std::set<MapLoadedCallback>::iterator cb_it = callbacks.begin(); cb_it != callbacks.end(); ++cb_it)
{
//ArLog::log(ArLog::Normal, "MapLoader::process(): invoking callback: %p", (void*)*cb_it);
invokeMapLoadedCallback(*cb_it, true, mapfile, map);