/
planner_3d.cpp
1831 lines (1637 loc) · 57.7 KB
/
planner_3d.cpp
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) 2014-2020, the neonavigation authors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <cmath>
#include <limits>
#include <list>
#include <string>
#include <utility>
#include <vector>
#include <omp.h>
#include <ros/ros.h>
#include <costmap_cspace_msgs/CSpace3D.h>
#include <costmap_cspace_msgs/CSpace3DUpdate.h>
#include <diagnostic_updater/diagnostic_updater.h>
#include <geometry_msgs/PoseArray.h>
#include <nav_msgs/GetPlan.h>
#include <nav_msgs/OccupancyGrid.h>
#include <nav_msgs/Path.h>
#include <planner_cspace_msgs/PlannerStatus.h>
#include <sensor_msgs/PointCloud.h>
#include <std_srvs/Empty.h>
#include <trajectory_tracker_msgs/PathWithVelocity.h>
#include <trajectory_tracker_msgs/converter.h>
#include <ros/console.h>
#include <tf2/utils.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_ros/transform_listener.h>
#include <actionlib/server/simple_action_server.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <planner_cspace_msgs/MoveWithToleranceAction.h>
#include <neonavigation_common/compatibility.h>
#include <planner_cspace/bbf.h>
#include <planner_cspace/grid_astar.h>
#include <planner_cspace/jump_detector.h>
#include <planner_cspace/planner_3d/costmap_bbf.h>
#include <planner_cspace/planner_3d/grid_astar_model.h>
#include <planner_cspace/planner_3d/grid_metric_converter.h>
#include <planner_cspace/planner_3d/motion_cache.h>
#include <planner_cspace/planner_3d/path_interpolator.h>
#include <planner_cspace/planner_3d/rotation_cache.h>
namespace planner_cspace
{
namespace planner_3d
{
class Planner3dNode
{
public:
using Astar = GridAstar<3, 2>;
protected:
using Planner3DActionServer = actionlib::SimpleActionServer<move_base_msgs::MoveBaseAction>;
using Planner3DTolerantActionServer = actionlib::SimpleActionServer<planner_cspace_msgs::MoveWithToleranceAction>;
ros::NodeHandle nh_;
ros::NodeHandle pnh_;
ros::Subscriber sub_map_;
ros::Subscriber sub_map_update_;
ros::Subscriber sub_goal_;
ros::Publisher pub_path_;
ros::Publisher pub_path_velocity_;
ros::Publisher pub_path_poses_;
ros::Publisher pub_hysteresis_map_;
ros::Publisher pub_distance_map_;
ros::Publisher pub_remembered_map_;
ros::Publisher pub_start_;
ros::Publisher pub_end_;
ros::Publisher pub_status_;
ros::ServiceServer srs_forget_;
ros::ServiceServer srs_make_plan_;
std::shared_ptr<Planner3DActionServer> act_;
std::shared_ptr<Planner3DTolerantActionServer> act_tolerant_;
planner_cspace_msgs::MoveWithToleranceGoalConstPtr goal_tolerant_;
tf2_ros::Buffer tfbuf_;
tf2_ros::TransformListener tfl_;
Astar as_;
Astar::Gridmap<char, 0x40> cm_;
Astar::Gridmap<char, 0x80> cm_rough_;
Astar::Gridmap<char, 0x40> cm_base_;
Astar::Gridmap<char, 0x80> cm_rough_base_;
Astar::Gridmap<char, 0x80> cm_hyst_;
Astar::Gridmap<char, 0x80> cm_updates_;
Astar::Gridmap<float> cost_estim_cache_;
CostmapBBF bbf_costmap_;
GridAstarModel3D::Ptr model_;
std::array<float, 1024> euclid_cost_lin_cache_;
costmap_cspace_msgs::MapMetaData3D map_info_;
std_msgs::Header map_header_;
float freq_;
float freq_min_;
float search_range_;
bool antialias_start_;
int range_;
int local_range_;
double local_range_f_;
int longcut_range_;
double longcut_range_f_;
int esc_range_;
int esc_angle_;
double esc_range_f_;
int tolerance_range_;
int tolerance_angle_;
double tolerance_range_f_;
double tolerance_angle_f_;
int unknown_cost_;
bool overwrite_cost_;
bool has_map_;
bool has_goal_;
bool has_start_;
bool has_hysteresis_map_;
bool goal_updated_;
bool remember_updates_;
bool fast_map_update_;
std::vector<Astar::Vec> search_list_;
std::vector<Astar::Vec> search_list_rough_;
double hist_ignore_range_f_;
int hist_ignore_range_;
double hist_ignore_range_max_f_;
int hist_ignore_range_max_;
bool temporary_escape_;
float remember_hit_odds_;
float remember_miss_odds_;
bool use_path_with_velocity_;
bool retain_last_error_status_;
JumpDetector jump_;
std::string robot_frame_;
int max_retry_num_;
int num_task_;
int num_cost_estim_task_;
// Cost weights
CostCoeff cc_;
geometry_msgs::PoseStamped start_;
geometry_msgs::PoseStamped goal_;
geometry_msgs::PoseStamped goal_raw_;
Astar::Vecf ec_;
double goal_tolerance_lin_f_;
double goal_tolerance_ang_f_;
double goal_tolerance_ang_finish_;
int goal_tolerance_lin_;
int goal_tolerance_ang_;
planner_cspace_msgs::PlannerStatus status_;
bool find_best_;
float sw_wait_;
float rough_cost_max_;
bool rough_;
bool force_goal_orientation_;
bool escaping_;
int cnt_stuck_;
diagnostic_updater::Updater diag_updater_;
ros::Duration costmap_watchdog_;
ros::Time last_costmap_;
bool cbForget(std_srvs::EmptyRequest& req,
std_srvs::EmptyResponse& res)
{
ROS_WARN("Forgetting remembered costmap.");
if (has_map_)
bbf_costmap_.clear();
return true;
}
bool cbMakePlan(nav_msgs::GetPlan::Request& req,
nav_msgs::GetPlan::Response& res)
{
if (!has_map_)
{
ROS_ERROR("make_plan service is called without map.");
return false;
}
if (req.start.header.frame_id != map_header_.frame_id ||
req.goal.header.frame_id != map_header_.frame_id)
{
ROS_ERROR("Start [%s] and Goal [%s] poses must be in the map frame [%s].",
req.start.header.frame_id.c_str(),
req.goal.header.frame_id.c_str(),
map_header_.frame_id.c_str());
return false;
}
Astar::Vec s, e;
grid_metric_converter::metric2Grid(
map_info_, s[0], s[1], s[2],
req.start.pose.position.x, req.start.pose.position.y, tf2::getYaw(req.start.pose.orientation));
s[2] = 0;
grid_metric_converter::metric2Grid(
map_info_, e[0], e[1], e[2],
req.goal.pose.position.x, req.goal.pose.position.y, tf2::getYaw(req.goal.pose.orientation));
e[2] = 0;
if (!(cm_rough_.validate(s, range_) && cm_rough_.validate(e, range_)))
{
ROS_ERROR("Given start or goal is not on the map.");
return false;
}
else if (cm_rough_[s] == 100 || cm_rough_[e] == 100)
{
ROS_ERROR(
"Given start or goal is in Rock. (start: %d, end: %d)",
cm_rough_[s], cm_rough_[e]);
return false;
}
const auto cb_progress = [](const std::list<Astar::Vec>& path_grid)
{
return true;
};
const auto ts = boost::chrono::high_resolution_clock::now();
GridAstarModel2D::Ptr model_2d(new GridAstarModel2D(model_));
std::list<Astar::Vec> path_grid;
std::vector<GridAstarModel3D::VecWithCost> starts;
starts.emplace_back(s);
if (!as_.search(
starts, e, path_grid,
model_2d,
cb_progress,
0, 1.0f / freq_min_, find_best_))
{
ROS_WARN("Path plan failed (goal unreachable)");
return false;
}
const auto tnow = boost::chrono::high_resolution_clock::now();
ROS_INFO("Path found (%0.4f sec.)",
boost::chrono::duration<float>(tnow - ts).count());
nav_msgs::Path path;
path.header = map_header_;
path.header.stamp = ros::Time::now();
const std::list<Astar::Vecf> path_interpolated =
model_->path_interpolator_.interpolate(path_grid, 0.5, 0.0);
grid_metric_converter::grid2MetricPath(map_info_, path_interpolated, path);
res.plan.header = map_header_;
res.plan.poses.resize(path.poses.size());
for (size_t i = 0; i < path.poses.size(); ++i)
{
res.plan.poses[i] = path.poses[i];
}
return true;
}
void cbGoal(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
if (act_->isActive() || act_tolerant_->isActive())
{
ROS_ERROR("Setting new goal is ignored since planner_3d is proceeding the action.");
return;
}
setGoal(*msg);
}
void cbPreempt()
{
ROS_WARN("Preempting the current goal.");
if (act_->isActive())
act_->setPreempted(move_base_msgs::MoveBaseResult(), "Preempted.");
if (act_tolerant_->isActive())
act_tolerant_->setPreempted(planner_cspace_msgs::MoveWithToleranceResult(), "Preempted.");
has_goal_ = false;
status_.status = planner_cspace_msgs::PlannerStatus::DONE;
}
bool setGoal(const geometry_msgs::PoseStamped& msg)
{
if (msg.header.frame_id != map_header_.frame_id)
{
ROS_ERROR("Goal [%s] pose must be in the map frame [%s].",
msg.header.frame_id.c_str(), map_header_.frame_id.c_str());
return false;
}
goal_raw_ = goal_ = msg;
const double len2 =
goal_.pose.orientation.x * goal_.pose.orientation.x +
goal_.pose.orientation.y * goal_.pose.orientation.y +
goal_.pose.orientation.z * goal_.pose.orientation.z +
goal_.pose.orientation.w * goal_.pose.orientation.w;
if (std::abs(len2 - 1.0) < 0.1)
{
escaping_ = false;
has_goal_ = true;
cnt_stuck_ = 0;
if (!updateGoal())
{
has_goal_ = false;
return false;
}
status_.status = planner_cspace_msgs::PlannerStatus::DOING;
pub_status_.publish(status_);
diag_updater_.update();
}
else
{
has_goal_ = false;
if (act_->isActive())
act_->setSucceeded(move_base_msgs::MoveBaseResult(), "Goal cleared.");
if (act_tolerant_->isActive())
act_tolerant_->setSucceeded(planner_cspace_msgs::MoveWithToleranceResult(), "Goal cleared.");
}
return true;
}
void fillCostmap(
reservable_priority_queue<Astar::PriorityVec>& open,
Astar::Gridmap<float>& g,
const Astar::Vec& s, const Astar::Vec& e)
{
const Astar::Vec s_rough(s[0], s[1], 0);
struct SearchDiffs
{
Astar::Vec d;
std::vector<Astar::Vec> pos;
float grid_to_len;
};
std::vector<SearchDiffs> search_diffs;
{
Astar::Vec d;
d[2] = 0;
const int range_rough = 4;
for (d[0] = -range_rough; d[0] <= range_rough; d[0]++)
{
for (d[1] = -range_rough; d[1] <= range_rough; d[1]++)
{
if (d[0] == 0 && d[1] == 0)
continue;
if (d.sqlen() > range_rough * range_rough)
continue;
SearchDiffs diffs;
const float grid_to_len = d.gridToLenFactor();
const int dist = d.len();
const float dpx = static_cast<float>(d[0]) / dist;
const float dpy = static_cast<float>(d[1]) / dist;
Astar::Vecf pos(0, 0, 0);
for (int i = 0; i < dist; i++)
{
Astar::Vec ipos(pos);
if (diffs.pos.size() == 0 || diffs.pos.back() != ipos)
{
diffs.pos.push_back(std::move(ipos));
}
pos[0] += dpx;
pos[1] += dpy;
}
diffs.grid_to_len = grid_to_len;
diffs.d = d;
search_diffs.push_back(std::move(diffs));
}
}
}
std::vector<Astar::PriorityVec> centers;
centers.reserve(num_cost_estim_task_);
#pragma omp parallel
{
std::vector<Astar::GridmapUpdate> updates;
updates.reserve(num_cost_estim_task_ * search_diffs.size() / omp_get_num_threads());
const float range_overshoot = ec_[0] * (range_ + local_range_ + longcut_range_);
while (true)
{
#pragma omp barrier
#pragma omp single
{
centers.clear();
for (size_t i = 0; i < static_cast<size_t>(num_cost_estim_task_);)
{
if (open.size() < 1)
break;
Astar::PriorityVec center(open.top());
open.pop();
if (center.p_raw_ > g[center.v_])
continue;
if (center.p_raw_ - range_overshoot > g[s_rough])
continue;
centers.emplace_back(std::move(center));
++i;
}
} // omp single
if (centers.size() == 0)
break;
updates.clear();
#pragma omp for schedule(static)
for (auto it = centers.cbegin(); it < centers.cend(); ++it)
{
const Astar::Vec p = it->v_;
for (const SearchDiffs& ds : search_diffs)
{
const Astar::Vec d = ds.d;
const Astar::Vec next = p + d;
if (static_cast<size_t>(next[0]) >= static_cast<size_t>(map_info_.width) ||
static_cast<size_t>(next[1]) >= static_cast<size_t>(map_info_.height))
continue;
float cost = model_->euclidCostRough(d);
const float gnext = g[next];
if (gnext < g[p] + cost)
{
// Skip as this search task has no chance to find better way.
continue;
}
{
float sum = 0, sum_hist = 0;
bool collision = false;
for (const auto& d : ds.pos)
{
const Astar::Vec pos = p + d;
const char c = cm_rough_[pos];
if (c > 99)
{
collision = true;
break;
}
sum += c;
sum_hist += bbf_costmap_.getCost(pos);
}
if (collision)
continue;
cost +=
(map_info_.linear_resolution * ds.grid_to_len / 100.0) *
(sum * cc_.weight_costmap_ + sum_hist * cc_.weight_remembered_);
if (cost < 0)
{
cost = 0;
ROS_WARN_THROTTLE(1.0, "Negative cost value is detected. Limited to zero.");
}
}
const float cost_next = it->p_raw_ + cost;
if (gnext > cost_next)
{
updates.emplace_back(p, next, cost_next, cost_next);
}
}
}
#pragma omp barrier
#pragma omp critical
{
for (const Astar::GridmapUpdate& u : updates)
{
if (g[u.getPos()] > u.getCost())
{
g[u.getPos()] = u.getCost();
open.push(std::move(u.getPriorityVec()));
}
}
} // omp critical
}
} // omp parallel
rough_cost_max_ = g[s_rough] + ec_[0] * (range_ + local_range_);
}
bool searchAvailablePos(Astar::Vec& s, const int xy_range, const int angle_range,
const int cost_acceptable = 50, const int min_xy_range = 0)
{
ROS_DEBUG("%d, %d (%d,%d,%d)", xy_range, angle_range, s[0], s[1], s[2]);
float range_min = std::numeric_limits<float>::max();
Astar::Vec s_out;
Astar::Vec d;
for (d[2] = -angle_range; d[2] <= angle_range; d[2]++)
{
for (d[0] = -xy_range; d[0] <= xy_range; d[0]++)
{
for (d[1] = -xy_range; d[1] <= xy_range; d[1]++)
{
if (d[0] == 0 && d[1] == 0 && d[2] == 0)
continue;
if (d.sqlen() > xy_range * xy_range)
continue;
if (d.sqlen() < min_xy_range * min_xy_range)
continue;
Astar::Vec s2 = s + d;
if ((unsigned int)s2[0] >= (unsigned int)map_info_.width ||
(unsigned int)s2[1] >= (unsigned int)map_info_.height)
continue;
s2.cycleUnsigned(map_info_.angle);
if (!cm_.validate(s2, range_))
continue;
if (cm_[s2] >= cost_acceptable)
continue;
const auto cost = model_->euclidCost(d);
if (cost < range_min)
{
range_min = cost;
s_out = s2;
}
}
}
}
if (range_min == std::numeric_limits<float>::max())
{
if (cost_acceptable != 100)
{
return searchAvailablePos(s, xy_range, angle_range, 100);
}
return false;
}
s = s_out;
s.cycleUnsigned(map_info_.angle);
ROS_DEBUG(" (%d,%d,%d)", s[0], s[1], s[2]);
return true;
}
bool updateGoal(const bool goal_changed = true)
{
if (!has_goal_)
return true;
if (!has_map_ || !has_start_)
{
ROS_ERROR("Goal received, however map/goal/start are not ready. (%d/%d/%d)",
static_cast<int>(has_map_), static_cast<int>(has_goal_), static_cast<int>(has_start_));
return true;
}
Astar::Vec s, e;
grid_metric_converter::metric2Grid(
map_info_, s[0], s[1], s[2],
start_.pose.position.x, start_.pose.position.y,
tf2::getYaw(start_.pose.orientation));
s.cycleUnsigned(map_info_.angle);
grid_metric_converter::metric2Grid(
map_info_, e[0], e[1], e[2],
goal_.pose.position.x, goal_.pose.position.y,
tf2::getYaw(goal_.pose.orientation));
e.cycleUnsigned(map_info_.angle);
if (goal_changed)
{
ROS_INFO(
"New goal received (%d, %d, %d)",
e[0], e[1], e[2]);
}
if (!cm_.validate(e, range_))
{
ROS_ERROR("Given goal is not on the map.");
return false;
}
if (!cm_.validate(s, range_))
{
ROS_ERROR("You are on the edge of the world.");
return false;
}
const auto ts = boost::chrono::high_resolution_clock::now();
reservable_priority_queue<Astar::PriorityVec> open;
open.reserve(map_info_.width * map_info_.height / 2);
cost_estim_cache_.clear(std::numeric_limits<float>::max());
if (cm_[e] == 100)
{
if (!searchAvailablePos(e, tolerance_range_, tolerance_angle_))
{
ROS_WARN("Oops! Goal is in Rock!");
++cnt_stuck_;
return true;
}
ROS_INFO("Goal moved (%d, %d, %d)",
e[0], e[1], e[2]);
float x, y, yaw;
grid_metric_converter::grid2Metric(map_info_, e[0], e[1], e[2], x, y, yaw);
goal_.pose.orientation = tf2::toMsg(tf2::Quaternion(tf2::Vector3(0.0, 0.0, 1.0), yaw));
goal_.pose.position.x = x;
goal_.pose.position.y = y;
}
if (cm_[s] == 100)
{
if (!searchAvailablePos(s, tolerance_range_, tolerance_angle_))
{
ROS_WARN("Oops! You are in Rock!");
return true;
}
}
e[2] = 0;
cost_estim_cache_[e] = -ec_[0] * 0.5; // Decrement to reduce calculation error
open.push(Astar::PriorityVec(cost_estim_cache_[e], cost_estim_cache_[e], e));
fillCostmap(open, cost_estim_cache_, s, e);
const auto tnow = boost::chrono::high_resolution_clock::now();
ROS_DEBUG("Cost estimation cache generated (%0.4f sec.)",
boost::chrono::duration<float>(tnow - ts).count());
cost_estim_cache_[e] = 0;
if (goal_changed)
{
cm_hyst_.clear(100);
has_hysteresis_map_ = false;
}
publishDebug();
goal_updated_ = true;
return true;
}
void publishDebug()
{
if (pub_distance_map_.getNumSubscribers() > 0)
{
sensor_msgs::PointCloud distance_map;
distance_map.header = map_header_;
distance_map.header.stamp = ros::Time::now();
for (Astar::Vec p(0, 0, 0); p[1] < cost_estim_cache_.size()[1]; p[1]++)
{
for (p[0] = 0; p[0] < cost_estim_cache_.size()[0]; p[0]++)
{
p[2] = 0;
float x, y, yaw;
grid_metric_converter::grid2Metric(map_info_, p[0], p[1], p[2], x, y, yaw);
geometry_msgs::Point32 point;
point.x = x;
point.y = y;
if (cost_estim_cache_[p] == std::numeric_limits<float>::max())
continue;
point.z = cost_estim_cache_[p] / 500;
distance_map.points.push_back(point);
}
}
pub_distance_map_.publish(distance_map);
}
if (pub_hysteresis_map_.getNumSubscribers() > 0)
{
nav_msgs::OccupancyGrid hysteresis_map;
hysteresis_map.header.frame_id = map_header_.frame_id;
hysteresis_map.info.resolution = map_info_.linear_resolution;
hysteresis_map.info.width = map_info_.width;
hysteresis_map.info.height = map_info_.height;
hysteresis_map.info.origin = map_info_.origin;
hysteresis_map.data.resize(map_info_.width * map_info_.height, 100);
for (Astar::Vec p(0, 0, 0); p[1] < cost_estim_cache_.size()[1]; p[1]++)
{
for (p[0] = 0; p[0] < cost_estim_cache_.size()[0]; p[0]++)
{
if (cost_estim_cache_[p] == std::numeric_limits<float>::max())
continue;
char cost = 100;
for (Astar::Vec p2 = p; p2[2] < static_cast<int>(map_info_.angle); ++p2[2])
{
cost = std::min(cm_hyst_[p2], cost);
}
hysteresis_map.data[p[0] + p[1] * map_info_.width] = cost;
}
}
pub_hysteresis_map_.publish(hysteresis_map);
}
}
void publishRememberedMap()
{
if (pub_remembered_map_.getNumSubscribers() > 0 && remember_updates_)
{
nav_msgs::OccupancyGrid remembered_map;
remembered_map.header.frame_id = map_header_.frame_id;
remembered_map.info.resolution = map_info_.linear_resolution;
remembered_map.info.width = map_info_.width;
remembered_map.info.height = map_info_.height;
remembered_map.info.origin = map_info_.origin;
remembered_map.data.resize(map_info_.width * map_info_.height);
const auto generate_pointcloud = [this, &remembered_map](const Astar::Vec& p, bbf::BinaryBayesFilter& bbf)
{
remembered_map.data[p[0] + p[1] * map_info_.width] =
(bbf.getProbability() - bbf::MIN_PROBABILITY) * 100 / (bbf::MAX_PROBABILITY - bbf::MIN_PROBABILITY);
};
bbf_costmap_.forEach(generate_pointcloud);
pub_remembered_map_.publish(remembered_map);
}
}
void publishEmptyPath()
{
nav_msgs::Path path;
path.header.frame_id = robot_frame_;
path.header.stamp = ros::Time::now();
if (use_path_with_velocity_)
{
pub_path_velocity_.publish(
trajectory_tracker_msgs::toPathWithVelocity(
path, std::numeric_limits<double>::quiet_NaN()));
}
else
{
pub_path_.publish(path);
}
}
void cbMapUpdate(const costmap_cspace_msgs::CSpace3DUpdate::ConstPtr& msg)
{
if (!has_map_)
return;
ROS_DEBUG("Map updated");
const ros::Time now = ros::Time::now();
last_costmap_ = now;
cm_ = cm_base_;
cm_rough_ = cm_rough_base_;
cm_updates_.clear(-1);
bool clear_hysteresis(false);
{
const Astar::Vec gp(
static_cast<int>(msg->x), static_cast<int>(msg->y), static_cast<int>(msg->yaw));
const Astar::Vec gp_rough(gp[0], gp[1], 0);
for (Astar::Vec p(0, 0, 0); p[0] < static_cast<int>(msg->width); p[0]++)
{
for (p[1] = 0; p[1] < static_cast<int>(msg->height); p[1]++)
{
int cost_min = 100;
for (p[2] = 0; p[2] < static_cast<int>(msg->angle); p[2]++)
{
const size_t addr = ((p[2] * msg->height) + p[1]) * msg->width + p[0];
const char c = msg->data[addr];
if (c < cost_min)
cost_min = c;
if (c == 100 && !clear_hysteresis && cm_hyst_[gp + p] == 0)
clear_hysteresis = true;
}
p[2] = 0;
cm_updates_[gp_rough + p] = cost_min;
if (cost_min > cm_rough_[gp_rough + p])
cm_rough_[gp_rough + p] = cost_min;
for (p[2] = 0; p[2] < static_cast<int>(msg->angle); p[2]++)
{
const size_t addr = ((p[2] * msg->height) + p[1]) * msg->width + p[0];
const char c = msg->data[addr];
if (overwrite_cost_)
{
if (c >= 0)
cm_[gp + p] = c;
}
else
{
if (cm_[gp + p] < c)
cm_[gp + p] = c;
}
}
}
}
}
if (clear_hysteresis && has_hysteresis_map_)
{
ROS_INFO("The previous path collides to the obstacle. Clearing hysteresis map.");
cm_hyst_.clear(100);
has_hysteresis_map_ = false;
}
if (!has_start_)
return;
Astar::Vec s;
grid_metric_converter::metric2Grid(
map_info_, s[0], s[1], s[2],
start_.pose.position.x, start_.pose.position.y,
tf2::getYaw(start_.pose.orientation));
s.cycleUnsigned(map_info_.angle);
if (remember_updates_)
{
bbf_costmap_.remember(
&cm_updates_, s,
remember_hit_odds_, remember_miss_odds_,
hist_ignore_range_, hist_ignore_range_max_);
publishRememberedMap();
bbf_costmap_.updateCostmap();
}
if (!has_goal_)
return;
if (!fast_map_update_)
{
updateGoal(false);
return;
}
Astar::Vec e;
grid_metric_converter::metric2Grid(
map_info_, e[0], e[1], e[2],
goal_.pose.position.x, goal_.pose.position.y,
tf2::getYaw(goal_.pose.orientation));
e.cycleUnsigned(map_info_.angle);
if (cm_[e] == 100)
{
updateGoal(false);
return;
}
e[2] = 0;
const auto ts = boost::chrono::high_resolution_clock::now();
Astar::Vec p, p_cost_min;
p[2] = 0;
float cost_min = std::numeric_limits<float>::max();
for (p[1] = static_cast<int>(msg->y); p[1] < static_cast<int>(msg->y + msg->height); p[1]++)
{
for (p[0] = static_cast<int>(msg->x); p[0] < static_cast<int>(msg->x + msg->width); p[0]++)
{
if (cost_min > cost_estim_cache_[p])
{
p_cost_min = p;
cost_min = cost_estim_cache_[p];
}
}
}
reservable_priority_queue<Astar::PriorityVec> open;
reservable_priority_queue<Astar::PriorityVec> erase;
open.reserve(map_info_.width * map_info_.height / 2);
erase.reserve(map_info_.width * map_info_.height / 2);
if (cost_min != std::numeric_limits<float>::max())
erase.emplace(cost_min, cost_min, p_cost_min);
while (true)
{
if (erase.size() < 1)
break;
const Astar::PriorityVec center(erase.top());
const Astar::Vec p = center.v_;
erase.pop();
if (cost_estim_cache_[p] == std::numeric_limits<float>::max())
continue;
cost_estim_cache_[p] = std::numeric_limits<float>::max();
Astar::Vec d;
d[2] = 0;
for (d[0] = -1; d[0] <= 1; d[0]++)
{
for (d[1] = -1; d[1] <= 1; d[1]++)
{
if (!((d[0] == 0) ^ (d[1] == 0)))
continue;
Astar::Vec next = p + d;
next[2] = 0;
if ((unsigned int)next[0] >= (unsigned int)map_info_.width ||
(unsigned int)next[1] >= (unsigned int)map_info_.height)
continue;
const float gn = cost_estim_cache_[next];
if (gn == std::numeric_limits<float>::max())
continue;
if (gn < cost_min)
{
open.emplace(gn, gn, next);
continue;
}
erase.emplace(gn, gn, next);
}
}
}
if (open.size() == 0)
{
open.emplace(-ec_[0] * 0.5, -ec_[0] * 0.5, e);
}
{
Astar::Vec p;
p[2] = 0;
for (p[0] = 0; p[0] < static_cast<int>(map_info_.width); p[0]++)
{
for (p[1] = 0; p[1] < static_cast<int>(map_info_.height); p[1]++)
{
const auto gp = cost_estim_cache_[p];
if (gp > rough_cost_max_)
{
open.emplace(gp, gp, p);
}
}
}
}
fillCostmap(open, cost_estim_cache_, s, e);
const auto tnow = boost::chrono::high_resolution_clock::now();
ROS_DEBUG("Cost estimation cache updated (%0.4f sec.)",
boost::chrono::duration<float>(tnow - ts).count());
publishDebug();
}
void cbMap(const costmap_cspace_msgs::CSpace3D::ConstPtr& msg)
{
ROS_INFO("Map received");
ROS_INFO(" linear_resolution %0.2f x (%dx%d) px", msg->info.linear_resolution,
msg->info.width, msg->info.height);
ROS_INFO(" angular_resolution %0.2f x %d px", msg->info.angular_resolution,
msg->info.angle);
ROS_INFO(" origin %0.3f m, %0.3f m, %0.3f rad",
msg->info.origin.position.x,
msg->info.origin.position.y,
tf2::getYaw(msg->info.origin.orientation));
// Stop robot motion until next planning step
publishEmptyPath();
ec_ = Astar::Vecf(
1.0f / cc_.max_vel_,
1.0f / cc_.max_vel_,
1.0f * cc_.weight_ang_vel_ / cc_.max_ang_vel_);
if (map_info_.linear_resolution != msg->info.linear_resolution ||
map_info_.angular_resolution != msg->info.angular_resolution)
{
map_info_ = msg->info;
range_ = static_cast<int>(search_range_ / map_info_.linear_resolution);
hist_ignore_range_ = std::lround(hist_ignore_range_f_ / map_info_.linear_resolution);
hist_ignore_range_max_ = std::lround(hist_ignore_range_max_f_ / map_info_.linear_resolution);
local_range_ = std::lround(local_range_f_ / map_info_.linear_resolution);
longcut_range_ = std::lround(longcut_range_f_ / map_info_.linear_resolution);
esc_range_ = std::lround(esc_range_f_ / map_info_.linear_resolution);
esc_angle_ = map_info_.angle / 8;
tolerance_range_ = std::lround(tolerance_range_f_ / map_info_.linear_resolution);
tolerance_angle_ = std::lround(tolerance_angle_f_ / map_info_.angular_resolution);
goal_tolerance_lin_ = std::lround(goal_tolerance_lin_f_ / map_info_.linear_resolution);
goal_tolerance_ang_ = std::lround(goal_tolerance_ang_f_ / map_info_.angular_resolution);
cc_.angle_resolution_aspect_ = 2.0 / tanf(map_info_.angular_resolution);
model_.reset(
new GridAstarModel3D(
map_info_,
ec_,
local_range_,
cost_estim_cache_, cm_, cm_hyst_, cm_rough_,
cc_, range_));
ROS_DEBUG("Search model updated");
}
else
{