]> rtime.felk.cvut.cz Git - hubacji1/rrts.git/blob - src/rrts.cc
Fix missing mtr for reeds shepp steering
[hubacji1/rrts.git] / src / rrts.cc
1 #include <algorithm>
2 #include "rrts.h"
3
4 #include "reeds_shepp.h"
5
6 template <typename T> int sgn(T val) {
7         return (T(0) < val) - (val < T(0));
8 }
9
10 RRTNode::RRTNode()
11 {
12 }
13
14 RRTNode::RRTNode(const BicycleCar &bc)
15 {
16     this->x(bc.x());
17     this->y(bc.y());
18     this->h(bc.h());
19     this->sp(bc.sp());
20     this->st(bc.st());
21 }
22
23 bool RRTNode::operator==(const RRTNode& n)
24 {
25         if (this == &n)
26                 return true;
27         return false;
28 }
29
30 Obstacle::Obstacle()
31 {
32 }
33
34 double RRTS::elapsed()
35 {
36         std::chrono::duration<double> dt;
37         dt = std::chrono::duration_cast<std::chrono::duration<double>>(
38                 std::chrono::high_resolution_clock::now()
39                 - this->tstart_
40         );
41         this->scnt_ = dt.count();
42         return this->scnt_;
43 }
44
45 bool RRTS::should_stop()
46 {
47         // the following counters must be updated, do not comment
48         this->icnt_++;
49         this->elapsed();
50         // current iteration stop conditions
51         if (this->should_finish()) return true;
52         if (this->should_break()) return true;
53         // but continue by default
54         return false;
55 }
56
57 bool RRTS::should_finish()
58 {
59         // decide finish conditions (maybe comment some lines)
60         //if (this->icnt_ > 999) return true;
61         if (this->scnt_ > 10) return true;
62         if (this->gf()) return true;
63         // but continue by default
64         return false;
65 }
66
67 bool RRTS::should_break()
68 {
69         // decide break conditions (maybe comment some lines)
70         //if (this->scnt_ - this->pcnt_ > 2) return true;
71         // but continue by default
72         return false;
73 }
74
75 bool RRTS::should_continue()
76 {
77         // decide the stop conditions (maybe comment some lines)
78         // it is exact opposite of `should_stop`
79         //if (this->icnt_ > 999) return false;
80         if (this->scnt_ > 10) return false;
81         if (this->gf()) return false;
82         // and reset pause counter if should continue
83         this->pcnt_ = this->scnt_;
84         return true;
85 }
86
87 void RRTS::store_node(RRTNode n)
88 {
89         this->nodes().push_back(n);
90 }
91
92 // RRT procedures
93 std::tuple<bool, unsigned int, unsigned int>
94 RRTS::collide(std::vector<std::tuple<double, double>> &poly)
95 {
96         for (auto &o: this->obstacles())
97                 if (std::get<0>(::collide(poly, o.poly())))
98                         return ::collide(poly, o.poly());
99         return std::make_tuple(false, 0, 0);
100 }
101
102 std::tuple<bool, unsigned int, unsigned int>
103 RRTS::collide_steered_from(RRTNode &f)
104 {
105         auto fbc = BicycleCar();
106         fbc.x(f.x());
107         fbc.y(f.y());
108         fbc.h(f.h());
109         std::vector<std::tuple<double, double>> s;
110         s.push_back(std::make_tuple(fbc.x(), fbc.y()));
111         for (auto &n: this->steered()) {
112                 auto nbc = BicycleCar();
113                 nbc.x(n.x());
114                 nbc.y(n.y());
115                 nbc.h(n.h());
116                 s.push_back(std::make_tuple(nbc.lfx(), nbc.lfy()));
117                 s.push_back(std::make_tuple(nbc.lrx(), nbc.lry()));
118                 s.push_back(std::make_tuple(nbc.rrx(), nbc.rry()));
119                 s.push_back(std::make_tuple(nbc.rfx(), nbc.rfy()));
120         }
121         auto col = this->collide(s);
122         auto strip_from = this->steered().size() - std::get<1>(col) / 4;
123         if (std::get<0>(col) && strip_from > 0) {
124                 while (strip_from-- > 0) {
125                         this->steered().pop_back();
126                 }
127                 return this->collide_steered_from(f);
128         }
129         return col;
130 }
131
132 std::tuple<bool, unsigned int, unsigned int>
133 RRTS::collide_two_nodes(RRTNode &f, RRTNode &t)
134 {
135         auto fbc = BicycleCar();
136         fbc.x(f.x());
137         fbc.y(f.y());
138         fbc.h(f.h());
139         auto tbc = BicycleCar();
140         tbc.x(f.x());
141         tbc.y(f.y());
142         tbc.h(f.h());
143         std::vector<std::tuple<double, double>> p;
144         p.push_back(std::make_tuple(fbc.lfx(), fbc.lfy()));
145         p.push_back(std::make_tuple(fbc.lrx(), fbc.lry()));
146         p.push_back(std::make_tuple(fbc.rrx(), fbc.rry()));
147         p.push_back(std::make_tuple(fbc.rfx(), fbc.rfy()));
148         p.push_back(std::make_tuple(tbc.lfx(), tbc.lfy()));
149         p.push_back(std::make_tuple(tbc.lrx(), tbc.lry()));
150         p.push_back(std::make_tuple(tbc.rrx(), tbc.rry()));
151         p.push_back(std::make_tuple(tbc.rfx(), tbc.rfy()));
152         return this->collide(p);
153 }
154
155 double RRTS::cost_build(RRTNode &f, RRTNode &t)
156 {
157         double cost = 0;
158         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
159         return cost;
160 }
161
162 double RRTS::cost_search(RRTNode &f, RRTNode &t)
163 {
164         double cost = 0;
165         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
166         return cost;
167 }
168
169 void RRTS::sample()
170 {
171         double x = 0;
172         double y = 0;
173         double h = 0;
174         switch (this->sample_dist_type()) {
175         case 1:
176                 x = this->udx_(this->gen_);
177                 y = this->udy_(this->gen_);
178                 h = this->udh_(this->gen_);
179                 break;
180         default:
181                 x = this->ndx_(this->gen_);
182                 y = this->ndy_(this->gen_);
183                 h = this->ndh_(this->gen_);
184         }
185         this->samples().push_back(RRTNode());
186         this->samples().back().x(x);
187         this->samples().back().y(y);
188         this->samples().back().h(h);
189 }
190
191 RRTNode *RRTS::nn(RRTNode &t)
192 {
193         RRTNode *nn = &this->nodes().front();
194         double cost = this->cost_search(*nn, t);
195         for (auto &f: this->nodes()) {
196                 if (this->cost_search(f, t) < cost) {
197                         nn = &f;
198                         cost = this->cost_search(f, t);
199                 }
200         }
201         return nn;
202 }
203
204 std::vector<RRTNode *> RRTS::nv(RRTNode &t)
205 {
206         std::vector<RRTNode *> nv;
207         double cost = std::min(GAMMA(this->nodes().size()), ETA);
208         for (auto &f: this->nodes())
209                 if (this->cost_search(f, t) < cost)
210                         nv.push_back(&f);
211         return nv;
212 }
213
214 int cb_rs_steer(double q[4], void *user_data)
215 {
216         std::vector<RRTNode> *nodes = (std::vector<RRTNode> *) user_data;
217         RRTNode *ln = nullptr;
218         if (nodes->size() > 0)
219                 ln = &nodes->back();
220         nodes->push_back(RRTNode());
221         nodes->back().x(q[0]);
222         nodes->back().y(q[1]);
223         nodes->back().h(q[2]);
224         nodes->back().sp(q[3]);
225         if (nodes->back().sp() == 0)
226                 nodes->back().set_t(RRTNodeType::cusp);
227         else if (ln != nullptr && sgn(ln->sp()) != sgn(nodes->back().sp()))
228                 ln->set_t(RRTNodeType::cusp);
229         return 0;
230 }
231
232 void RRTS::steer(RRTNode &f, RRTNode &t)
233 {
234         this->steered().clear();
235         double q0[] = {f.x(), f.y(), f.h()};
236         double q1[] = {t.x(), t.y(), t.h()};
237         ReedsSheppStateSpace rsss(this->bc.mtr());
238         rsss.sample(q0, q1, 0.5, cb_rs_steer, &this->steered());
239 }
240
241 void RRTS::join_steered(RRTNode *f)
242 {
243         while (this->steered().size() > 0) {
244                 this->store_node(this->steered().front());
245                 RRTNode *t = &this->nodes().back();
246                 t->p(f);
247                 t->c(this->cost_build(*f, *t));
248                 this->steered().erase(this->steered().begin());
249                 f = t;
250         }
251 }
252
253 bool RRTS::goal_found(RRTNode &f)
254 {
255         auto &g = this->goals().front();
256         double cost = this->cost_build(f, g);
257         double edist = sqrt(
258                 pow(f.x() - g.x(), 2)
259                 + pow(f.y() - g.y(), 2)
260         );
261         double adist = std::abs(f.h() - g.h());
262         if (edist < 0.05 && adist < M_PI / 32) {
263                 if (g.p() == nullptr || cc(f) + cost < cc(g)) {
264                         g.p(&f);
265                         g.c(cost);
266                 }
267                 return true;
268         }
269         return false;
270 }
271
272 // RRT* procedures
273 bool RRTS::connect()
274 {
275         RRTNode *t = &this->steered().front();
276         RRTNode *f = this->nn(this->samples().back());
277         double cost = this->cost_search(*f, *t);
278         for (auto n: this->nv(*t)) {
279                 if (
280                         !std::get<0>(this->collide_two_nodes(*n, *t))
281                         && this->cost_search(*n, *t) < cost
282                 ) {
283                         f = n;
284                         cost = this->cost_search(*n, *t);
285                 }
286         }
287         this->store_node(this->steered().front());
288         t = &this->nodes().back();
289         t->p(f);
290         t->c(this->cost_build(*f, *t));
291         t->set_t(RRTNodeType::connected);
292         return true;
293 }
294
295 void RRTS::rewire()
296 {
297         RRTNode *f = &this->nodes().back();
298         for (auto n: this->nv(*f)) {
299                 if (
300                         !std::get<0>(this->collide_two_nodes(*f, *n))
301                         && cc(*f) + this->cost_search(*f, *n) < cc(*n)
302                 ) {
303                         n->p(f);
304                         n->c(this->cost_build(*f, *n));
305                 }
306         }
307 }
308
309 // API
310 void RRTS::init()
311 {
312 }
313
314 void RRTS::deinit()
315 {
316         this->nodes().clear();
317         this->samples().clear();
318         this->steered().clear();
319         this->store_node(RRTNode()); // root
320         this->icnt_ = 0;
321         this->scnt_ = 0;
322         this->pcnt_ = 0;
323         this->gf_ = false;
324 }
325
326 std::vector<RRTNode *> RRTS::path()
327 {
328         std::vector<RRTNode *> path;
329         if (this->goals().size() == 0)
330                 return path;
331         RRTNode *goal = &this->goals().front();
332         if (goal->p() == nullptr)
333                 return path;
334         while (goal != nullptr) {
335                 path.push_back(goal);
336                 goal = goal->p();
337         }
338         std::reverse(path.begin(), path.end());
339         return path;
340 }
341
342 bool RRTS::next()
343 {
344         if (this->icnt_ == 0)
345                 this->tstart_ = std::chrono::high_resolution_clock::now();
346         bool next = true;
347         if (this->should_stop())
348                 return false;
349         this->sample();
350         this->steer(
351                 *this->nn(this->samples().back()),
352                 this->samples().back()
353         );
354         if (std::get<0>(this->collide_steered_from(
355                 *this->nn(this->samples().back())
356         )))
357                 return next;
358         if (!this->connect())
359                 return next;
360         this->rewire();
361         unsigned scnt = this->steered().size();
362         this->join_steered(&this->nodes().back());
363         RRTNode *just_added = &this->nodes().back();
364         while (scnt > 0) {
365                 scnt--;
366                 auto &g = this->goals().front();
367                 this->steer(*just_added, g);
368                 if (std::get<0>(this->collide_steered_from(
369                         *just_added
370                 )))
371                         continue;
372                 this->join_steered(just_added);
373                 this->gf(this->goal_found(this->nodes().back()));
374                 just_added = just_added->p();
375         }
376         return next;
377 }
378
379 void RRTS::set_sample_normal(
380         double mx, double dx,
381         double my, double dy,
382         double mh, double dh
383 )
384 {
385         this->ndx_ = std::normal_distribution<double>(mx, dx);
386         this->ndy_ = std::normal_distribution<double>(my, dy);
387         this->ndh_ = std::normal_distribution<double>(mh, dh);
388 }
389 void RRTS::set_sample_uniform(
390         double xmin, double xmax,
391         double ymin, double ymax,
392         double hmin, double hmax
393 )
394 {
395         this->udx_ = std::uniform_real_distribution<double>(xmin,xmax);
396         this->udy_ = std::uniform_real_distribution<double>(ymin,ymax);
397         this->udh_ = std::uniform_real_distribution<double>(hmin,hmax);
398 }
399 void RRTS::set_sample(
400         double x1, double x2,
401         double y1, double y2,
402         double h1, double h2
403 )
404 {
405         switch (this->sample_dist_type()) {
406         case 1:
407                 x1 += this->nodes().front().x();
408                 x2 += this->nodes().front().x();
409                 y1 += this->nodes().front().y();
410                 y2 += this->nodes().front().y();
411                 this->set_sample_uniform(x1, x2, y1, y2, h1, h2);
412                 break;
413         default:
414                 this->set_sample_normal(x1, x2, y1, y2, h1, h2);
415         }
416 }
417
418 Json::Value RRTS::json()
419 {
420         Json::Value jvo;
421         {
422                 jvo["time"] = this->scnt();
423         }
424         {
425                 jvo["iterations"] = this->icnt();
426         }
427         {
428                 jvo["init"][0] = this->nodes().front().x();
429                 jvo["init"][1] = this->nodes().front().y();
430                 jvo["init"][2] = this->nodes().front().h();
431         }
432         {
433                 if (this->path().size() > 0) {
434                         jvo["cost"] = cc(*this->path().back());
435                         jvo["goal"][0] = this->path().back()->x();
436                         jvo["goal"][1] = this->path().back()->y();
437                         jvo["goal"][2] = this->path().back()->h();
438                 }
439         }
440         {
441                 unsigned int cu = 0;
442                 unsigned int co = 0;
443                 unsigned int pcnt = 0;
444                 for (auto n: this->path()) {
445                         jvo["path"][pcnt][0] = n->x();
446                         jvo["path"][pcnt][1] = n->y();
447                         jvo["path"][pcnt][2] = n->h();
448                         if (n->t(RRTNodeType::cusp))
449                                 cu++;
450                         if (n->t(RRTNodeType::connected))
451                                 co++;
452                         pcnt++;
453                 }
454                 jvo["cusps-in-path"] = cu;
455                 jvo["connecteds-in-path"] = co;
456         }
457         {
458                 unsigned int gcnt = 0;
459                 for (auto g: this->goals()) {
460                         jvo["goals"][gcnt][0] = g.x();
461                         jvo["goals"][gcnt][1] = g.y();
462                         jvo["goals"][gcnt][2] = g.h();
463                         gcnt++;
464                 }
465         }
466         {
467                 unsigned int ocnt = 0;
468                 for (auto o: this->obstacles()) {
469                         unsigned int ccnt = 0;
470                         for (auto c: o.poly()) {
471                                 jvo["obst"][ocnt][ccnt][0] = std::get<0>(c);
472                                 jvo["obst"][ocnt][ccnt][1] = std::get<1>(c);
473                                 ccnt++;
474                         }
475                         ocnt++;
476                 }
477         }
478         {
479                 jvo["nodes"] = (unsigned int) this->nodes().size();
480         }
481         //{
482         //        unsigned int ncnt = 0;
483         //        for (auto n: this->nodes()) {
484         //                jvo["nodes_x"][ncnt] = n.x();
485         //                jvo["nodes_y"][ncnt] = n.y();
486         //                //jvo["nodes_h"][ncnt] = n.h();
487         //                ncnt++;
488         //        }
489         //}
490         return jvo;
491 }
492
493 void RRTS::json(Json::Value jvi)
494 {
495         assert(jvi["init"] != Json::nullValue);
496         assert(jvi["goal"] != Json::nullValue);
497         assert(jvi["goals"] != Json::nullValue);
498         assert(jvi["obst"] != Json::nullValue);
499
500         this->nodes().front().x(jvi["init"][0].asDouble());
501         this->nodes().front().y(jvi["init"][1].asDouble());
502         this->nodes().front().h(jvi["init"][2].asDouble());
503         {
504                 RRTNode tmp_node;
505                 tmp_node.x(jvi["goal"][0].asDouble());
506                 tmp_node.y(jvi["goal"][1].asDouble());
507                 tmp_node.h(jvi["goal"][2].asDouble());
508                 this->goals().push_back(tmp_node);
509                 for (auto g: jvi["goals"]) {
510                         tmp_node.x(g[0].asDouble());
511                         tmp_node.y(g[1].asDouble());
512                         tmp_node.h(g[2].asDouble());
513                         this->goals().push_back(tmp_node);
514                 }
515         }
516         {
517                 Obstacle tmp_obstacle;
518                 for (auto o: jvi["obst"]) {
519                         tmp_obstacle.poly().clear();
520                         for (auto c: o) {
521                                 double tmp_x = c[0].asDouble();
522                                 double tmp_y = c[1].asDouble();
523                                 auto tmp_tuple = std::make_tuple(tmp_x, tmp_y);
524                                 tmp_obstacle.poly().push_back(tmp_tuple);
525                         }
526                         this->obstacles().push_back(tmp_obstacle);
527                 }
528         }
529         {
530                 double edist_init_goal = sqrt(
531                         pow(
532                                 this->nodes().front().x()
533                                 - this->goals().front().x(),
534                                 2
535                         )
536                         + pow(
537                                 this->nodes().front().y()
538                                 - this->goals().front().y(),
539                                 2
540                         )
541                 );
542                 this->set_sample(
543                         this->nodes().front().x(), edist_init_goal,
544                         this->nodes().front().y(), edist_init_goal,
545                         0, 2 * M_PI
546                 );
547         }
548 }
549
550 RRTS::RRTS()
551         : gen_(std::random_device{}())
552 {
553         this->goals().reserve(100);
554         this->nodes().reserve(4000000);
555         this->samples().reserve(1000);
556         this->steered().reserve(20000);
557         this->store_node(RRTNode()); // root
558 }
559
560 double cc(RRTNode &t)
561 {
562         RRTNode *n = &t;
563         double cost = 0;
564         while (n != nullptr) {
565                 cost += n->c();
566                 n = n->p();
567         }
568         return cost;
569 }