]> rtime.felk.cvut.cz Git - hubacji1/rrts.git/blob - src/rrts.cc
Add setting of uniform circle sampling dist type
[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_uniform_circle()
407 {
408         this->udx_ = std::uniform_real_distribution<double>(0, 1);
409         this->udy_ = std::uniform_real_distribution<double>(0, 1);
410         this->udh_ = std::uniform_real_distribution<double>(0, 2 * M_PI);
411 }
412 void RRTS::set_sample(
413         double x1, double x2,
414         double y1, double y2,
415         double h1, double h2
416 )
417 {
418         switch (this->sample_dist_type()) {
419         case 1: // uniform
420                 x1 += this->nodes().front().x();
421                 x2 += this->nodes().front().x();
422                 y1 += this->nodes().front().y();
423                 y2 += this->nodes().front().y();
424                 this->set_sample_uniform(x1, x2, y1, y2, h1, h2);
425                 break;
426         case 2: // uniform circle
427                 this->set_sample_uniform_circle();
428                 break;
429         default: // normal
430                 this->set_sample_normal(x1, x2, y1, y2, h1, h2);
431         }
432 }
433
434 Json::Value RRTS::json()
435 {
436         Json::Value jvo;
437         {
438                 jvo["time"] = this->scnt();
439         }
440         {
441                 jvo["iterations"] = this->icnt();
442         }
443         {
444                 jvo["init"][0] = this->nodes().front().x();
445                 jvo["init"][1] = this->nodes().front().y();
446                 jvo["init"][2] = this->nodes().front().h();
447         }
448         {
449                 if (this->path().size() > 0) {
450                         jvo["cost"] = cc(*this->path().back());
451                         jvo["goal"][0] = this->path().back()->x();
452                         jvo["goal"][1] = this->path().back()->y();
453                         jvo["goal"][2] = this->path().back()->h();
454                 }
455         }
456         {
457                 unsigned int cu = 0;
458                 unsigned int co = 0;
459                 unsigned int pcnt = 0;
460                 for (auto n: this->path()) {
461                         jvo["path"][pcnt][0] = n->x();
462                         jvo["path"][pcnt][1] = n->y();
463                         jvo["path"][pcnt][2] = n->h();
464                         if (n->t(RRTNodeType::cusp))
465                                 cu++;
466                         if (n->t(RRTNodeType::connected))
467                                 co++;
468                         pcnt++;
469                 }
470                 jvo["cusps-in-path"] = cu;
471                 jvo["connecteds-in-path"] = co;
472         }
473         {
474                 unsigned int gcnt = 0;
475                 for (auto g: this->goals()) {
476                         jvo["goals"][gcnt][0] = g.x();
477                         jvo["goals"][gcnt][1] = g.y();
478                         jvo["goals"][gcnt][2] = g.h();
479                         gcnt++;
480                 }
481         }
482         {
483                 unsigned int ocnt = 0;
484                 for (auto o: this->obstacles()) {
485                         unsigned int ccnt = 0;
486                         for (auto c: o.poly()) {
487                                 jvo["obst"][ocnt][ccnt][0] = std::get<0>(c);
488                                 jvo["obst"][ocnt][ccnt][1] = std::get<1>(c);
489                                 ccnt++;
490                         }
491                         ocnt++;
492                 }
493         }
494         {
495                 jvo["nodes"] = (unsigned int) this->nodes().size();
496         }
497         //{
498         //        unsigned int ncnt = 0;
499         //        for (auto n: this->nodes()) {
500         //                jvo["nodes_x"][ncnt] = n.x();
501         //                jvo["nodes_y"][ncnt] = n.y();
502         //                //jvo["nodes_h"][ncnt] = n.h();
503         //                ncnt++;
504         //        }
505         //}
506         return jvo;
507 }
508
509 void RRTS::json(Json::Value jvi)
510 {
511         assert(jvi["init"] != Json::nullValue);
512         assert(jvi["goal"] != Json::nullValue);
513         assert(jvi["goals"] != Json::nullValue);
514         assert(jvi["obst"] != Json::nullValue);
515
516         this->nodes().front().x(jvi["init"][0].asDouble());
517         this->nodes().front().y(jvi["init"][1].asDouble());
518         this->nodes().front().h(jvi["init"][2].asDouble());
519         {
520                 RRTNode tmp_node;
521                 tmp_node.x(jvi["goal"][0].asDouble());
522                 tmp_node.y(jvi["goal"][1].asDouble());
523                 tmp_node.h(jvi["goal"][2].asDouble());
524                 this->goals().push_back(tmp_node);
525                 for (auto g: jvi["goals"]) {
526                         tmp_node.x(g[0].asDouble());
527                         tmp_node.y(g[1].asDouble());
528                         tmp_node.h(g[2].asDouble());
529                         this->goals().push_back(tmp_node);
530                 }
531         }
532         {
533                 Obstacle tmp_obstacle;
534                 for (auto o: jvi["obst"]) {
535                         tmp_obstacle.poly().clear();
536                         for (auto c: o) {
537                                 double tmp_x = c[0].asDouble();
538                                 double tmp_y = c[1].asDouble();
539                                 auto tmp_tuple = std::make_tuple(tmp_x, tmp_y);
540                                 tmp_obstacle.poly().push_back(tmp_tuple);
541                         }
542                         this->obstacles().push_back(tmp_obstacle);
543                 }
544         }
545         {
546                 double edist_init_goal = sqrt(
547                         pow(
548                                 this->nodes().front().x()
549                                 - this->goals().front().x(),
550                                 2
551                         )
552                         + pow(
553                                 this->nodes().front().y()
554                                 - this->goals().front().y(),
555                                 2
556                         )
557                 );
558                 this->set_sample(
559                         this->nodes().front().x(), edist_init_goal,
560                         this->nodes().front().y(), edist_init_goal,
561                         0, 2 * M_PI
562                 );
563         }
564 }
565
566 RRTS::RRTS()
567         : gen_(std::random_device{}())
568 {
569         this->goals().reserve(100);
570         this->nodes().reserve(4000000);
571         this->samples().reserve(1000);
572         this->steered().reserve(20000);
573         this->store_node(RRTNode()); // root
574 }
575
576 double cc(RRTNode &t)
577 {
578         RRTNode *n = &t;
579         double cost = 0;
580         while (n != nullptr) {
581                 cost += n->c();
582                 n = n->p();
583         }
584         return cost;
585 }