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