]> rtime.felk.cvut.cz Git - hubacji1/rrts.git/blob - src/rrts.cc
Fix sampling in circle
[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 void RRTS::log_path_cost()
46 {
47         this->log_path_cost_.push_back(cc(this->goals().front()));
48         this->log_path_time_ += 0.1;
49 }
50
51 bool RRTS::should_stop()
52 {
53         // the following counters must be updated, do not comment
54         this->icnt_++;
55         this->elapsed();
56         // current iteration stop conditions
57         if (this->should_finish()) return true;
58         if (this->should_break()) return true;
59         // but continue by default
60         return false;
61 }
62
63 bool RRTS::should_finish()
64 {
65         // decide finish conditions (maybe comment some lines)
66         //if (this->icnt_ > 999) return true;
67         if (this->scnt_ > 2) return true;
68         if (this->finishit) return true;
69         //if (this->gf()) return true;
70         // but continue by default
71         return false;
72 }
73
74 bool RRTS::should_break()
75 {
76         // decide break conditions (maybe comment some lines)
77         //if (this->scnt_ - this->pcnt_ > 2) return true;
78         // but continue by default
79         return false;
80 }
81
82 bool RRTS::should_continue()
83 {
84         // decide the stop conditions (maybe comment some lines)
85         // it is exact opposite of `should_stop`
86         //if (this->icnt_ > 999) return false;
87         if (this->scnt_ > 10) return false;
88         if (this->gf()) return false;
89         // and reset pause counter if should continue
90         this->pcnt_ = this->scnt_;
91         return true;
92 }
93
94 void RRTS::store_node(RRTNode n)
95 {
96         this->nodes().push_back(n);
97 }
98
99 // RRT procedures
100 std::tuple<bool, unsigned int, unsigned int>
101 RRTS::collide(std::vector<std::tuple<double, double>> &poly)
102 {
103         for (auto &o: this->obstacles())
104                 if (std::get<0>(::collide(poly, o.poly())))
105                         return ::collide(poly, o.poly());
106         return std::make_tuple(false, 0, 0);
107 }
108
109 std::tuple<bool, unsigned int, unsigned int>
110 RRTS::collide_steered_from(RRTNode &f)
111 {
112         auto fbc = BicycleCar();
113         fbc.x(f.x());
114         fbc.y(f.y());
115         fbc.h(f.h());
116         std::vector<std::tuple<double, double>> s;
117         s.push_back(std::make_tuple(fbc.x(), fbc.y()));
118         for (auto &n: this->steered()) {
119                 auto nbc = BicycleCar();
120                 nbc.x(n.x());
121                 nbc.y(n.y());
122                 nbc.h(n.h());
123                 s.push_back(std::make_tuple(nbc.lfx(), nbc.lfy()));
124                 s.push_back(std::make_tuple(nbc.lrx(), nbc.lry()));
125                 s.push_back(std::make_tuple(nbc.rrx(), nbc.rry()));
126                 s.push_back(std::make_tuple(nbc.rfx(), nbc.rfy()));
127         }
128         auto col = this->collide(s);
129         auto strip_from = this->steered().size() - std::get<1>(col) / 4;
130         if (std::get<0>(col) && strip_from > 0) {
131                 while (strip_from-- > 0) {
132                         this->steered().pop_back();
133                 }
134                 return this->collide_steered_from(f);
135         }
136         return col;
137 }
138
139 std::tuple<bool, unsigned int, unsigned int>
140 RRTS::collide_two_nodes(RRTNode &f, RRTNode &t)
141 {
142         auto fbc = BicycleCar();
143         fbc.x(f.x());
144         fbc.y(f.y());
145         fbc.h(f.h());
146         auto tbc = BicycleCar();
147         tbc.x(f.x());
148         tbc.y(f.y());
149         tbc.h(f.h());
150         std::vector<std::tuple<double, double>> p;
151         p.push_back(std::make_tuple(fbc.lfx(), fbc.lfy()));
152         p.push_back(std::make_tuple(fbc.lrx(), fbc.lry()));
153         p.push_back(std::make_tuple(fbc.rrx(), fbc.rry()));
154         p.push_back(std::make_tuple(fbc.rfx(), fbc.rfy()));
155         p.push_back(std::make_tuple(tbc.lfx(), tbc.lfy()));
156         p.push_back(std::make_tuple(tbc.lrx(), tbc.lry()));
157         p.push_back(std::make_tuple(tbc.rrx(), tbc.rry()));
158         p.push_back(std::make_tuple(tbc.rfx(), tbc.rfy()));
159         return this->collide(p);
160 }
161
162 double RRTS::cost_build(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 double RRTS::cost_search(RRTNode &f, RRTNode &t)
170 {
171         double cost = 0;
172         cost = sqrt(pow(t.y() - f.y(), 2) + pow(t.x() - f.x(), 2));
173         return cost;
174 }
175
176 void RRTS::sample()
177 {
178         double x = 0;
179         double y = 0;
180         double h = 0;
181         switch (this->sample_dist_type()) {
182         case 1: // uniform
183                 x = this->udx_(this->gen_);
184                 y = this->udy_(this->gen_);
185                 h = this->udh_(this->gen_);
186                 break;
187         case 2: // uniform circle
188         {
189                 // see https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly/50746409#50746409
190                 double R = sqrt(
191                         pow(
192                                 this->nodes().front().x()
193                                 - this->goals().front().x(),
194                                 2
195                         )
196                         + pow(
197                                 this->nodes().front().y()
198                                 - this->goals().front().y(),
199                                 2
200                         )
201                 );
202                 double a = atan2(
203                         this->goals().front().y() - this->nodes().front().y(),
204                         this->goals().front().x() - this->nodes().front().x()
205                 );
206                 double cx = this->goals().front().x() - R/2 * cos(a);
207                 double cy = this->goals().front().y() - R/2 * sin(a);
208                 double r = R * sqrt(this->udx_(this->gen_));
209                 double theta = this->udy_(this->gen_) * 2 * M_PI;
210                 x = cx + r * cos(theta);
211                 y = cy + r * sin(theta);
212                 h = this->udh_(this->gen_);
213         }
214                 break;
215         case 3: {
216                 this->udi_ = std::uniform_int_distribution<unsigned int>(
217                         0,
218                         this->nodes().size() - 1
219                 );
220                 auto ind = this->udi_(this->gen_);
221                 auto n = this->nodes()[ind];
222                 x = n.x();
223                 y = n.y();
224                 h = n.h();
225                 break;
226                 }
227         default: // normal
228                 x = this->ndx_(this->gen_);
229                 y = this->ndy_(this->gen_);
230                 h = this->ndh_(this->gen_);
231         }
232         this->samples().push_back(RRTNode());
233         this->samples().back().x(x);
234         this->samples().back().y(y);
235         this->samples().back().h(h);
236 }
237
238 RRTNode *RRTS::nn(RRTNode &t)
239 {
240         RRTNode *nn = &this->nodes().front();
241         double cost = this->cost_search(*nn, t);
242         for (auto &f: this->nodes()) {
243                 if (this->cost_search(f, t) < cost) {
244                         nn = &f;
245                         cost = this->cost_search(f, t);
246                 }
247         }
248         return nn;
249 }
250
251 std::vector<RRTNode *> RRTS::nv(RRTNode &t)
252 {
253         std::vector<RRTNode *> nv;
254         double cost = std::min(GAMMA(this->nodes().size()), ETA);
255         for (auto &f: this->nodes())
256                 if (this->cost_search(f, t) < cost)
257                         nv.push_back(&f);
258         return nv;
259 }
260
261 int cb_rs_steer(double q[4], void *user_data)
262 {
263         std::vector<RRTNode> *nodes = (std::vector<RRTNode> *) user_data;
264         RRTNode *ln = nullptr;
265         if (nodes->size() > 0)
266                 ln = &nodes->back();
267         nodes->push_back(RRTNode());
268         nodes->back().x(q[0]);
269         nodes->back().y(q[1]);
270         nodes->back().h(q[2]);
271         nodes->back().sp(q[3]);
272         if (nodes->back().sp() == 0)
273                 nodes->back().set_t(RRTNodeType::cusp);
274         else if (ln != nullptr && sgn(ln->sp()) != sgn(nodes->back().sp()))
275                 ln->set_t(RRTNodeType::cusp);
276         return 0;
277 }
278
279 void RRTS::steer(RRTNode &f, RRTNode &t)
280 {
281         this->steered().clear();
282         double q0[] = {f.x(), f.y(), f.h()};
283         double q1[] = {t.x(), t.y(), t.h()};
284         ReedsSheppStateSpace rsss(this->bc.mtr());
285         rsss.sample(q0, q1, 0.05, cb_rs_steer, &this->steered());
286 }
287
288 void RRTS::steer1(RRTNode &f, RRTNode &t)
289 {
290     return this->steer(f, t);
291 }
292
293 void RRTS::steer2(RRTNode &f, RRTNode &t)
294 {
295     return this->steer(f, t);
296 }
297
298 void RRTS::join_steered(RRTNode *f)
299 {
300         while (this->steered().size() > 0) {
301                 this->store_node(this->steered().front());
302                 RRTNode *t = &this->nodes().back();
303                 t->p(f);
304                 t->c(this->cost_build(*f, *t));
305                 this->steered().erase(this->steered().begin());
306                 f = t;
307         }
308 }
309
310 bool RRTS::goal_found(RRTNode &f)
311 {
312         auto &g = this->goals().front();
313         double cost = this->cost_build(f, g);
314         double edist = sqrt(
315                 pow(f.x() - g.x(), 2)
316                 + pow(f.y() - g.y(), 2)
317         );
318         double adist = std::abs(f.h() - g.h());
319         if (edist < 0.05 && adist < M_PI / 32) {
320                 if (g.p() == nullptr || cc(f) + cost < cc(g)) {
321                         g.p(&f);
322                         g.c(cost);
323                 }
324                 return true;
325         }
326         return false;
327 }
328
329 // RRT* procedures
330 bool RRTS::connect()
331 {
332         RRTNode *t = &this->steered().front();
333         RRTNode *f = this->nn(this->samples().back());
334         double cost = this->cost_search(*f, *t);
335         for (auto n: this->nv(*t)) {
336                 if (
337                         !std::get<0>(this->collide_two_nodes(*n, *t))
338                         && this->cost_search(*n, *t) < cost
339                 ) {
340                         f = n;
341                         cost = this->cost_search(*n, *t);
342                 }
343         }
344         this->store_node(this->steered().front());
345         t = &this->nodes().back();
346         t->p(f);
347         t->c(this->cost_build(*f, *t));
348         t->set_t(RRTNodeType::connected);
349         return true;
350 }
351
352 void RRTS::rewire()
353 {
354         RRTNode *f = &this->nodes().back();
355         for (auto n: this->nv(*f)) {
356                 if (
357                         !std::get<0>(this->collide_two_nodes(*f, *n))
358                         && cc(*f) + this->cost_search(*f, *n) < cc(*n)
359                 ) {
360                         n->p(f);
361                         n->c(this->cost_build(*f, *n));
362                 }
363         }
364 }
365
366 // API
367 void RRTS::init()
368 {
369 }
370
371 void RRTS::deinit()
372 {
373         this->nodes().clear();
374         this->samples().clear();
375         this->steered().clear();
376         this->store_node(RRTNode()); // root
377         this->icnt_ = 0;
378         this->scnt_ = 0;
379         this->pcnt_ = 0;
380         this->gf_ = false;
381 }
382
383 std::vector<RRTNode *> RRTS::path()
384 {
385         std::vector<RRTNode *> path;
386         if (this->goals().size() == 0)
387                 return path;
388         RRTNode *goal = &this->goals().back();
389         if (goal->p() == nullptr)
390                 return path;
391         while (goal != nullptr) {
392                 path.push_back(goal);
393                 goal = goal->p();
394         }
395         std::reverse(path.begin(), path.end());
396         return path;
397 }
398
399 bool RRTS::next()
400 {
401         if (this->icnt_ == 0)
402                 this->tstart_ = std::chrono::high_resolution_clock::now();
403         bool next = true;
404         if (this->scnt_ > this->log_path_time_)
405             this->log_path_cost();
406         if (this->should_stop())
407                 return false;
408         if (this->samples().size() == 0) {
409                 this->samples().push_back(RRTNode());
410                 this->samples().back().x(this->goals().front().x());
411                 this->samples().back().y(this->goals().front().y());
412                 this->samples().back().h(this->goals().front().h());
413         } else {
414                 this->sample();
415         }
416         this->steer1(
417                 *this->nn(this->samples().back()),
418                 this->samples().back()
419         );
420         if (this->steered().size() == 0)
421                 return next;
422         auto col = this->collide_steered_from(
423                 *this->nn(this->samples().back())
424         );
425         if (std::get<0>(col)) {
426                 auto rcnt = this->steered().size() - std::get<1>(col);
427                 while (rcnt-- > 0) {
428                         this->steered().pop_back();
429                 }
430         }
431         if (!this->connect())
432                 return next;
433         this->rewire();
434         unsigned scnt = this->steered().size();
435         this->join_steered(&this->nodes().back());
436         RRTNode *just_added = &this->nodes().back();
437         while (scnt > 0) {
438                 scnt--;
439                 auto &g = this->goals().front();
440                 this->steer2(*just_added, g);
441                 if (std::get<0>(this->collide_steered_from(
442                         *just_added
443                 )))
444                         continue;
445                 this->join_steered(just_added);
446                 this->gf(this->goal_found(this->nodes().back()));
447                 just_added = just_added->p();
448         }
449         return next;
450 }
451
452 void RRTS::set_sample_normal(
453         double mx, double dx,
454         double my, double dy,
455         double mh, double dh
456 )
457 {
458         this->ndx_ = std::normal_distribution<double>(mx, dx);
459         this->ndy_ = std::normal_distribution<double>(my, dy);
460         this->ndh_ = std::normal_distribution<double>(mh, dh);
461 }
462 void RRTS::set_sample_uniform(
463         double xmin, double xmax,
464         double ymin, double ymax,
465         double hmin, double hmax
466 )
467 {
468         this->udx_ = std::uniform_real_distribution<double>(xmin,xmax);
469         this->udy_ = std::uniform_real_distribution<double>(ymin,ymax);
470         this->udh_ = std::uniform_real_distribution<double>(hmin,hmax);
471 }
472 void RRTS::set_sample_uniform_circle()
473 {
474         this->udx_ = std::uniform_real_distribution<double>(0, 1);
475         this->udy_ = std::uniform_real_distribution<double>(0, 1);
476         this->udh_ = std::uniform_real_distribution<double>(0, 2 * M_PI);
477 }
478 void RRTS::set_sample(
479         double x1, double x2,
480         double y1, double y2,
481         double h1, double h2
482 )
483 {
484         switch (this->sample_dist_type()) {
485         case 1: // uniform
486                 x1 += this->nodes().front().x();
487                 x2 += this->nodes().front().x();
488                 y1 += this->nodes().front().y();
489                 y2 += this->nodes().front().y();
490                 this->set_sample_uniform(x1, x2, y1, y2, h1, h2);
491                 break;
492         case 2: // uniform circle
493                 this->set_sample_uniform_circle();
494                 break;
495         case 3: // uniform index of node in nodes
496                 this->set_sample_uniform_circle();
497                 break;
498         default: // normal
499                 this->set_sample_normal(x1, x2, y1, y2, h1, h2);
500         }
501 }
502
503 Json::Value RRTS::json()
504 {
505         Json::Value jvo;
506         {
507                 jvo["time"] = this->scnt();
508         }
509         {
510                 jvo["iterations"] = this->icnt();
511         }
512         {
513                 jvo["init"][0] = this->nodes().front().x();
514                 jvo["init"][1] = this->nodes().front().y();
515                 jvo["init"][2] = this->nodes().front().h();
516         }
517         {
518                 jvo["path_cost_before_opt"] = this->path_cost_before_opt_;
519         }
520         {
521                 if (this->path().size() > 0) {
522                         jvo["cost"] = cc(*this->path().back());
523                         jvo["entry"][0] = this->goals().front().x();
524                         jvo["entry"][1] = this->goals().front().y();
525                         jvo["entry"][2] = this->goals().front().h();
526                         jvo["goal"][0] = this->goals().back().x();
527                         jvo["goal"][1] = this->goals().back().y();
528                         jvo["goal"][2] = this->goals().back().h();
529                 }
530         }
531         {
532                 unsigned int cu = 0;
533                 unsigned int co = 0;
534                 unsigned int pcnt = 0;
535                 for (auto n: this->path()) {
536                         jvo["path"][pcnt][0] = n->x();
537                         jvo["path"][pcnt][1] = n->y();
538                         jvo["path"][pcnt][2] = n->h();
539                         if (n->t(RRTNodeType::cusp))
540                                 cu++;
541                         if (n->t(RRTNodeType::connected))
542                                 co++;
543                         pcnt++;
544                 }
545                 jvo["cusps-in-path"] = cu;
546                 jvo["connecteds-in-path"] = co;
547         }
548         {
549                 unsigned int gcnt = 0;
550                 for (auto g: this->goals()) {
551                         jvo["goals"][gcnt][0] = g.x();
552                         jvo["goals"][gcnt][1] = g.y();
553                         jvo["goals"][gcnt][2] = g.h();
554                         gcnt++;
555                 }
556         }
557         {
558                 unsigned int ocnt = 0;
559                 for (auto o: this->obstacles()) {
560                         unsigned int ccnt = 0;
561                         for (auto c: o.poly()) {
562                                 jvo["obst"][ocnt][ccnt][0] = std::get<0>(c);
563                                 jvo["obst"][ocnt][ccnt][1] = std::get<1>(c);
564                                 ccnt++;
565                         }
566                         ocnt++;
567                 }
568         }
569         {
570                 jvo["nodes"] = (unsigned int) this->nodes().size();
571         }
572         {
573                 unsigned int cnt = 0;
574                 for (auto i: this->log_path_cost_)
575                         jvo["log_path_cost"][cnt++] = i;
576         }
577         //{
578         //        unsigned int ncnt = 0;
579         //        for (auto n: this->nodes()) {
580         //                jvo["nodes_x"][ncnt] = n.x();
581         //                jvo["nodes_y"][ncnt] = n.y();
582         //                //jvo["nodes_h"][ncnt] = n.h();
583         //                ncnt++;
584         //        }
585         //}
586         return jvo;
587 }
588
589 void RRTS::json(Json::Value jvi)
590 {
591         assert(jvi["init"] != Json::nullValue);
592         assert(jvi["goals"] != Json::nullValue);
593         assert(jvi["obst"] != Json::nullValue);
594
595         this->nodes().front().x(jvi["init"][0].asDouble());
596         this->nodes().front().y(jvi["init"][1].asDouble());
597         this->nodes().front().h(jvi["init"][2].asDouble());
598         {
599                 RRTNode* gp = nullptr;
600                 if (jvi["entry"] != Json::nullValue) {
601                         this->entry_set = true;
602                         this->entry.x = jvi["entry"][0].asDouble();
603                         this->entry.y = jvi["entry"][1].asDouble();
604                         this->entry.b = jvi["entry"][2].asDouble();
605                         this->entry.e = jvi["entry"][3].asDouble();
606                         RRTNode tmp_node;
607                         tmp_node.x(this->entry.x);
608                         tmp_node.y(this->entry.y);
609                         tmp_node.h((this->entry.b + this->entry.e) / 2.0);
610                         this->goals().push_back(tmp_node);
611                         this->goals().back().p(gp);
612                         gp = &this->goals().back();
613                 }
614                 for (auto g: jvi["goals"]) {
615                         RRTNode tmp_node;
616                         tmp_node.x(g[0].asDouble());
617                         tmp_node.y(g[1].asDouble());
618                         tmp_node.h(g[2].asDouble());
619                         this->goals().push_back(tmp_node);
620                         this->goals().back().p(gp);
621                         gp = &this->goals().back();
622                 }
623                 this->goals().front().set_t(RRTNodeType::cusp);
624                 this->goals().back().set_t(RRTNodeType::cusp);
625         }
626         {
627                 Obstacle tmp_obstacle;
628                 for (auto o: jvi["obst"]) {
629                         tmp_obstacle.poly().clear();
630                         for (auto c: o) {
631                                 double tmp_x = c[0].asDouble();
632                                 double tmp_y = c[1].asDouble();
633                                 auto tmp_tuple = std::make_tuple(tmp_x, tmp_y);
634                                 tmp_obstacle.poly().push_back(tmp_tuple);
635                         }
636                         this->obstacles().push_back(tmp_obstacle);
637                 }
638         }
639         {
640                 double edist_init_goal = sqrt(
641                         pow(
642                                 this->nodes().front().x()
643                                 - this->goals().front().x(),
644                                 2
645                         )
646                         + pow(
647                                 this->nodes().front().y()
648                                 - this->goals().front().y(),
649                                 2
650                         )
651                 );
652                 this->set_sample(
653                         this->nodes().front().x(), edist_init_goal,
654                         this->nodes().front().y(), edist_init_goal,
655                         0, 2 * M_PI
656                 );
657         }
658 }
659
660 RRTS::RRTS()
661         : gen_(std::random_device{}())
662 {
663         this->goals().reserve(100);
664         this->nodes().reserve(4000000);
665         this->samples().reserve(1000);
666         this->steered().reserve(20000);
667         this->store_node(RRTNode()); // root
668 }
669
670 double cc(RRTNode &t)
671 {
672         RRTNode *n = &t;
673         double cost = 0;
674         while (n != nullptr) {
675                 cost += n->c();
676                 n = n->p();
677         }
678         return cost;
679 }