]> rtime.felk.cvut.cz Git - hubacji1/rrts.git/blob - src/rrts.cc
Test goal first, then random sample
[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         if (this->samples().size() == 0) {
350                 this->samples().push_back(RRTNode());
351                 this->samples().back().x(this->goals().front().x());
352                 this->samples().back().y(this->goals().front().y());
353                 this->samples().back().h(this->goals().front().h());
354         } else {
355                 this->sample();
356         }
357         this->steer(
358                 *this->nn(this->samples().back()),
359                 this->samples().back()
360         );
361         if (std::get<0>(this->collide_steered_from(
362                 *this->nn(this->samples().back())
363         )))
364                 return next;
365         if (!this->connect())
366                 return next;
367         this->rewire();
368         unsigned scnt = this->steered().size();
369         this->join_steered(&this->nodes().back());
370         RRTNode *just_added = &this->nodes().back();
371         while (scnt > 0) {
372                 scnt--;
373                 auto &g = this->goals().front();
374                 this->steer(*just_added, g);
375                 if (std::get<0>(this->collide_steered_from(
376                         *just_added
377                 )))
378                         continue;
379                 this->join_steered(just_added);
380                 this->gf(this->goal_found(this->nodes().back()));
381                 just_added = just_added->p();
382         }
383         return next;
384 }
385
386 void RRTS::set_sample_normal(
387         double mx, double dx,
388         double my, double dy,
389         double mh, double dh
390 )
391 {
392         this->ndx_ = std::normal_distribution<double>(mx, dx);
393         this->ndy_ = std::normal_distribution<double>(my, dy);
394         this->ndh_ = std::normal_distribution<double>(mh, dh);
395 }
396 void RRTS::set_sample_uniform(
397         double xmin, double xmax,
398         double ymin, double ymax,
399         double hmin, double hmax
400 )
401 {
402         this->udx_ = std::uniform_real_distribution<double>(xmin,xmax);
403         this->udy_ = std::uniform_real_distribution<double>(ymin,ymax);
404         this->udh_ = std::uniform_real_distribution<double>(hmin,hmax);
405 }
406 void RRTS::set_sample(
407         double x1, double x2,
408         double y1, double y2,
409         double h1, double h2
410 )
411 {
412         switch (this->sample_dist_type()) {
413         case 1:
414                 x1 += this->nodes().front().x();
415                 x2 += this->nodes().front().x();
416                 y1 += this->nodes().front().y();
417                 y2 += this->nodes().front().y();
418                 this->set_sample_uniform(x1, x2, y1, y2, h1, h2);
419                 break;
420         default:
421                 this->set_sample_normal(x1, x2, y1, y2, h1, h2);
422         }
423 }
424
425 Json::Value RRTS::json()
426 {
427         Json::Value jvo;
428         {
429                 jvo["time"] = this->scnt();
430         }
431         {
432                 jvo["iterations"] = this->icnt();
433         }
434         {
435                 jvo["init"][0] = this->nodes().front().x();
436                 jvo["init"][1] = this->nodes().front().y();
437                 jvo["init"][2] = this->nodes().front().h();
438         }
439         {
440                 if (this->path().size() > 0) {
441                         jvo["cost"] = cc(*this->path().back());
442                         jvo["goal"][0] = this->path().back()->x();
443                         jvo["goal"][1] = this->path().back()->y();
444                         jvo["goal"][2] = this->path().back()->h();
445                 }
446         }
447         {
448                 unsigned int cu = 0;
449                 unsigned int co = 0;
450                 unsigned int pcnt = 0;
451                 for (auto n: this->path()) {
452                         jvo["path"][pcnt][0] = n->x();
453                         jvo["path"][pcnt][1] = n->y();
454                         jvo["path"][pcnt][2] = n->h();
455                         if (n->t(RRTNodeType::cusp))
456                                 cu++;
457                         if (n->t(RRTNodeType::connected))
458                                 co++;
459                         pcnt++;
460                 }
461                 jvo["cusps-in-path"] = cu;
462                 jvo["connecteds-in-path"] = co;
463         }
464         {
465                 unsigned int gcnt = 0;
466                 for (auto g: this->goals()) {
467                         jvo["goals"][gcnt][0] = g.x();
468                         jvo["goals"][gcnt][1] = g.y();
469                         jvo["goals"][gcnt][2] = g.h();
470                         gcnt++;
471                 }
472         }
473         {
474                 unsigned int ocnt = 0;
475                 for (auto o: this->obstacles()) {
476                         unsigned int ccnt = 0;
477                         for (auto c: o.poly()) {
478                                 jvo["obst"][ocnt][ccnt][0] = std::get<0>(c);
479                                 jvo["obst"][ocnt][ccnt][1] = std::get<1>(c);
480                                 ccnt++;
481                         }
482                         ocnt++;
483                 }
484         }
485         {
486                 jvo["nodes"] = (unsigned int) this->nodes().size();
487         }
488         //{
489         //        unsigned int ncnt = 0;
490         //        for (auto n: this->nodes()) {
491         //                jvo["nodes_x"][ncnt] = n.x();
492         //                jvo["nodes_y"][ncnt] = n.y();
493         //                //jvo["nodes_h"][ncnt] = n.h();
494         //                ncnt++;
495         //        }
496         //}
497         return jvo;
498 }
499
500 void RRTS::json(Json::Value jvi)
501 {
502         assert(jvi["init"] != Json::nullValue);
503         assert(jvi["goal"] != Json::nullValue);
504         assert(jvi["goals"] != Json::nullValue);
505         assert(jvi["obst"] != Json::nullValue);
506
507         this->nodes().front().x(jvi["init"][0].asDouble());
508         this->nodes().front().y(jvi["init"][1].asDouble());
509         this->nodes().front().h(jvi["init"][2].asDouble());
510         {
511                 RRTNode tmp_node;
512                 tmp_node.x(jvi["goal"][0].asDouble());
513                 tmp_node.y(jvi["goal"][1].asDouble());
514                 tmp_node.h(jvi["goal"][2].asDouble());
515                 this->goals().push_back(tmp_node);
516                 for (auto g: jvi["goals"]) {
517                         tmp_node.x(g[0].asDouble());
518                         tmp_node.y(g[1].asDouble());
519                         tmp_node.h(g[2].asDouble());
520                         this->goals().push_back(tmp_node);
521                 }
522         }
523         {
524                 Obstacle tmp_obstacle;
525                 for (auto o: jvi["obst"]) {
526                         tmp_obstacle.poly().clear();
527                         for (auto c: o) {
528                                 double tmp_x = c[0].asDouble();
529                                 double tmp_y = c[1].asDouble();
530                                 auto tmp_tuple = std::make_tuple(tmp_x, tmp_y);
531                                 tmp_obstacle.poly().push_back(tmp_tuple);
532                         }
533                         this->obstacles().push_back(tmp_obstacle);
534                 }
535         }
536         {
537                 double edist_init_goal = sqrt(
538                         pow(
539                                 this->nodes().front().x()
540                                 - this->goals().front().x(),
541                                 2
542                         )
543                         + pow(
544                                 this->nodes().front().y()
545                                 - this->goals().front().y(),
546                                 2
547                         )
548                 );
549                 this->set_sample(
550                         this->nodes().front().x(), edist_init_goal,
551                         this->nodes().front().y(), edist_init_goal,
552                         0, 2 * M_PI
553                 );
554         }
555 }
556
557 RRTS::RRTS()
558         : gen_(std::random_device{}())
559 {
560         this->goals().reserve(100);
561         this->nodes().reserve(4000000);
562         this->samples().reserve(1000);
563         this->steered().reserve(20000);
564         this->store_node(RRTNode()); // root
565 }
566
567 double cc(RRTNode &t)
568 {
569         RRTNode *n = &t;
570         double cost = 0;
571         while (n != nullptr) {
572                 cost += n->c();
573                 n = n->p();
574         }
575         return cost;
576 }