]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - base/rrtbase.cc
Use normal distribution in sampling
[hubacji1/iamcar.git] / base / rrtbase.cc
1 /*
2 This file is part of I am car.
3
4 I am car is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 I am car is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with I am car. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <algorithm>
19 #include <cmath>
20 #include <omp.h>
21 #include <queue>
22 #include "bcar.h"
23 #include "rrtbase.h"
24
25 #if USE_GL > 0
26 // OpenGL
27 #include <GL/gl.h>
28 #include <GL/glu.h>
29 #include <SDL2/SDL.h>
30 #endif
31
32 // RRT
33 #include "sample.h"
34 #include "cost.h"
35 #include "steer.h"
36 #include "nn.h"
37 #include "nv.h"
38
39 #if USE_GL > 0
40 extern SDL_Window* gw;
41 extern SDL_GLContext gc;
42 #endif
43
44 Cell::Cell()
45 {
46         pthread_mutex_init(&this->m_, NULL);
47 }
48
49 bool Cell::changed()
50 {
51         pthread_mutex_lock(&this->m_);
52         bool ret = this->changed_;
53         pthread_mutex_unlock(&this->m_);
54         return ret;
55 }
56
57 std::vector<RRTNode *> Cell::nodes()
58 {
59         pthread_mutex_lock(&this->m_);
60         std::vector<RRTNode *> ret(this->nodes_);
61         pthread_mutex_unlock(&this->m_);
62         return ret;
63 }
64
65 void Cell::add_node(RRTNode *n)
66 {
67         pthread_mutex_lock(&this->m_);
68         this->nodes_.push_back(n);
69         this->changed_ = true;
70         pthread_mutex_unlock(&this->m_);
71 }
72
73 RRTBase::~RRTBase()
74 {
75 // Fix heap-use-after-free error when T3 planner is used. If only T2 is used,
76 // please uncommend the following code:
77 //
78         for (auto n: this->nodes_)
79                 if (n != this->root_)
80                         delete n;
81         for (auto n: this->dnodes_)
82                 if (n != this->root_ && n != this->goal_)
83                         delete n;
84         for (auto s: this->samples_)
85                 if (s != this->goal_)
86                         delete s;
87         for (auto edges: this->rlog_)
88                 for (auto e: edges)
89                         delete e;
90         delete this->root_;
91         delete this->goal_;
92 }
93
94 RRTBase::RRTBase()
95         : root_(new RRTNode())
96         , goal_(new RRTNode())
97         , gen_(std::random_device{}())
98         , ndx_(HMAX - HMIN, (HMAX - HMIN) / 4)
99         , ndy_(VMAX - VMIN, (VMAX - VMIN) / 4)
100         , ndh_(0, M_PI * 2 / 4)
101 {
102         this->nodes_.reserve(NOFNODES);
103         this->nodes_.push_back(this->root_);
104         this->add_iy(this->root_);
105         this->add_ixy(this->root_);
106 }
107
108 RRTBase::RRTBase(RRTNode *init, RRTNode *goal)
109         : root_(init)
110         , goal_(goal)
111         , gen_(std::random_device{}())
112         , ndx_(HMIN + (HMAX - HMIN) / 2, (HMAX - HMIN) / 4)
113         , ndy_(VMIN + (VMAX - VMIN) / 2, (VMAX - VMIN) / 4)
114         , ndh_(0, M_PI * 2 / 4)
115 {
116         this->nodes_.reserve(NOFNODES);
117         this->nodes_.push_back(init);
118         this->add_iy(init);
119         this->add_ixy(init);
120 }
121
122 // getter
123 RRTNode *RRTBase::root()
124 {
125         return this->root_;
126 }
127
128 RRTNode *RRTBase::goal()
129 {
130         return this->goal_;
131 }
132
133 std::vector<RRTNode *> &RRTBase::goals()
134 {
135         return this->goals_;
136 }
137
138 std::vector<RRTNode *> &RRTBase::nodes()
139 {
140         return this->nodes_;
141 }
142
143 std::vector<RRTNode *> &RRTBase::dnodes()
144 {
145         return this->dnodes_;
146 }
147
148 std::queue<RRTNode *> &RRTBase::firsts()
149 {
150         return this->firsts_;
151 }
152
153 PolygonObstacle &RRTBase::frame()
154 {
155         return this->frame_;
156 }
157
158 std::vector<RRTNode *> &RRTBase::samples()
159 {
160         return this->samples_;
161 }
162
163 std::vector<CircleObstacle> *RRTBase::co()
164 {
165         return this->cobstacles_;
166 }
167
168 std::vector<SegmentObstacle> *RRTBase::so()
169 {
170         return this->sobstacles_;
171 }
172
173 std::vector<float> &RRTBase::clog()
174 {
175         return this->clog_;
176 }
177
178 std::vector<float> &RRTBase::nlog()
179 {
180         return this->nlog_;
181 }
182
183 std::vector<std::vector<RRTEdge *>> &RRTBase::rlog()
184 {
185         return this->rlog_;
186 }
187
188 std::vector<float> &RRTBase::slog()
189 {
190         return this->slog_;
191 }
192
193 std::vector<std::vector<RRTNode *>> &RRTBase::tlog()
194 {
195         return this->tlog_;
196 }
197
198 std::vector<RRTNode *> &RRTBase::slot_cusp()
199 {
200         return this->slot_cusp_;
201 }
202
203 bool RRTBase::goal_found()
204 {
205         return this->goal_found_;
206 }
207
208 float RRTBase::elapsed()
209 {
210         std::chrono::duration<float> dt;
211         dt = std::chrono::duration_cast<std::chrono::duration<float>>(
212                         this->tend_ - this->tstart_);
213         return dt.count();
214 }
215
216 std::vector<RRTNode *> RRTBase::traj_cusp()
217 {
218         std::vector<RRTNode *> tmp_cusps;
219         for (auto n: this->tlog().back()) {
220                 if (sgn(n->s()) == 0) {
221                         tmp_cusps.push_back(n);
222                 } else if (n->parent() &&
223                                 sgn(n->s()) != sgn(n->parent()->s())) {
224                         tmp_cusps.push_back(n);
225                         tmp_cusps.push_back(n->parent());
226                 }
227         }
228         std::vector<RRTNode *> cusps;
229         for (unsigned int i = 0; i < tmp_cusps.size(); i++) {
230                 if (tmp_cusps[i] != tmp_cusps[(i + 1) % tmp_cusps.size()])
231                         cusps.push_back(tmp_cusps[i]);
232         }
233         return cusps;
234 }
235
236 // setter
237 void RRTBase::root(RRTNode *node)
238 {
239         this->root_ = node;
240 }
241
242 void RRTBase::goal(RRTNode *node)
243 {
244         this->goal_ = node;
245 }
246
247 void RRTBase::goals(std::vector<RRTNode *> g)
248 {
249         this->goals_ = g;
250         std::reverse(this->goals_.begin(), this->goals_.end());
251         RRTNode *pn = this->goals_.front();
252         for (auto n: this->goals_) {
253                 if (n != pn) {
254                         pn->add_child(n, this->cost(pn ,n));
255                         pn = n;
256                 }
257         }
258 }
259
260 bool RRTBase::logr(RRTNode *root)
261 {
262         std::vector<RRTEdge *> e; // Edges to log
263         std::vector<RRTNode *> s; // DFS stack
264         std::vector<RRTNode *> r; // reset visited_
265         RRTNode *tmp;
266         s.push_back(root);
267         while (s.size() > 0) {
268                 tmp = s.back();
269                 s.pop_back();
270                 if (!tmp->visit()) {
271                         r.push_back(tmp);
272                         for (auto ch: tmp->children()) {
273                                 s.push_back(ch);
274                                 e.push_back(new RRTEdge(tmp, ch));
275                         }
276                 }
277         }
278         for (auto n: r)
279                 n->visit(false);
280         this->rlog_.push_back(e);
281         return true;
282 }
283
284 float RRTBase::ocost(RRTNode *n)
285 {
286         float dist = 9999;
287         for (auto o: *this->cobstacles_)
288                 if (o.dist_to(n) < dist)
289                         dist = o.dist_to(n);
290         for (auto o: *this->sobstacles_)
291                 if (o.dist_to(n) < dist)
292                         dist = o.dist_to(n);
293         return n->ocost(dist);
294 }
295
296 bool RRTBase::tlog(std::vector<RRTNode *> t)
297 {
298         if (t.size() > 0) {
299                 this->slog_.push_back(this->elapsed());
300                 this->clog_.push_back(t.front()->ccost() - t.back()->ccost());
301                 this->nlog_.push_back(this->nodes_.size());
302                 this->tlog_.push_back(t);
303                 return true;
304         } else {
305                 return false;
306         }
307 }
308
309 void RRTBase::tstart()
310 {
311         this->tstart_ = std::chrono::high_resolution_clock::now();
312 }
313
314 void RRTBase::tend()
315 {
316         this->tend_ = std::chrono::high_resolution_clock::now();
317 }
318
319 bool RRTBase::link_obstacles(
320                 std::vector<CircleObstacle> *cobstacles,
321                 std::vector<SegmentObstacle> *sobstacles)
322 {
323         this->cobstacles_ = cobstacles;
324         this->sobstacles_ = sobstacles;
325         if (!this->cobstacles_ || !this->sobstacles_) {
326                 return false;
327         }
328         return true;
329 }
330
331 bool RRTBase::add_iy(RRTNode *n)
332 {
333         int i = IYI(n->y());
334         if (i < 0)
335                 i = 0;
336         if (i >= IYSIZE)
337                 i = IYSIZE - 1;
338         this->iy_[i].push_back(n);
339         return true;
340 }
341
342 bool RRTBase::add_ixy(RRTNode *n)
343 {
344         int ix = IXI(n->x());
345         if (ix < 0)
346                 ix = 0;
347         if (ix >= IXSIZE)
348                 ix = IXSIZE - 1;
349         int iy = IYI(n->y());
350         if (iy < 0)
351                 iy = 0;
352         if (iy >= IYSIZE)
353                 iy = IYSIZE - 1;
354         this->ixy_[ix][iy].add_node(n);
355         return true;
356 }
357
358 bool RRTBase::goal_found(bool f)
359 {
360         this->goal_found_ = f;
361         return f;
362 }
363
364 void RRTBase::slot_cusp(std::vector<RRTNode *> sc)
365 {
366         for (unsigned int i = 0; i < sc.size() - 1; i++)
367                 sc[i]->add_child(sc[i + 1], this->cost(sc[i], sc[i + 1]));
368         sc[0]->parent(this->goal());
369         this->slot_cusp_ = sc;
370 }
371
372 // other
373 bool RRTBase::glplot()
374 {
375 #if USE_GL > 0
376         glClear(GL_COLOR_BUFFER_BIT);
377         glLineWidth(1);
378         glPointSize(1);
379         // Plot obstacles
380         glBegin(GL_LINES);
381         for (auto o: *this->sobstacles_) {
382                 glColor3f(0, 0, 0);
383                 glVertex2f(GLVERTEX(o.init()));
384                 glVertex2f(GLVERTEX(o.goal()));
385         }
386         glEnd();
387         // Plot root, goal
388         glPointSize(8);
389         glBegin(GL_POINTS);
390         glColor3f(1, 0, 0);
391         glVertex2f(GLVERTEX(this->root_));
392         glVertex2f(GLVERTEX(this->goal_));
393         glEnd();
394         // Plot last sample
395         if (this->samples_.size() > 0) {
396                 glPointSize(8);
397                 glBegin(GL_POINTS);
398                 glColor3f(0, 1, 0);
399                 glVertex2f(GLVERTEX(this->samples_.back()));
400                 glEnd();
401         }
402         // Plot nodes
403         std::vector<RRTNode *> s; // DFS stack
404         std::vector<RRTNode *> r; // reset visited_
405         RRTNode *tmp;
406         glBegin(GL_LINES);
407         s.push_back(this->root_);
408         while (s.size() > 0) {
409                 tmp = s.back();
410                 s.pop_back();
411                 if (!tmp->visit()) {
412                         r.push_back(tmp);
413                         for (auto ch: tmp->children()) {
414                                 s.push_back(ch);
415                                 glColor3f(0.5, 0.5, 0.5);
416                                 glVertex2f(GLVERTEX(tmp));
417                                 glVertex2f(GLVERTEX(ch));
418                         }
419                 }
420         }
421         glEnd();
422         // Plot nodes (from goal)
423         glBegin(GL_LINES);
424         s.push_back(this->goal_);
425         while (s.size() > 0) {
426                 tmp = s.back();
427                 s.pop_back();
428                 if (!tmp->visit()) {
429                         r.push_back(tmp);
430                         for (auto ch: tmp->children()) {
431                                 s.push_back(ch);
432                                 glColor3f(0.5, 0.5, 0.5);
433                                 glVertex2f(GLVERTEX(tmp));
434                                 glVertex2f(GLVERTEX(ch));
435                         }
436                 }
437         }
438         glEnd();
439         std::vector<RRTNode *> cusps;
440         // Plot last trajectory
441         if (this->tlog().size() > 0) {
442                 glLineWidth(2);
443                 glBegin(GL_LINES);
444                 for (auto n: this->tlog().back()) {
445                         if (n->parent()) {
446                                 glColor3f(0, 0, 1);
447                                 glVertex2f(GLVERTEX(n));
448                                 glVertex2f(GLVERTEX(n->parent()));
449                                 if (sgn(n->s()) != sgn(n->parent()->s()))
450                                         cusps.push_back(n);
451                         }
452                 }
453                 glEnd();
454         }
455         // Plot cusps
456         glPointSize(8);
457         glBegin(GL_POINTS);
458         for (auto n: cusps) {
459                 glColor3f(0, 0, 1);
460                 glVertex2f(GLVERTEX(n));
461         }
462         glEnd();
463         SDL_GL_SwapWindow(gw);
464         for (auto n: r)
465                 n->visit(false);
466 #endif
467         return true;
468 }
469
470 bool RRTBase::goal_found(
471                 RRTNode *node,
472                 float (*cost)(RRTNode *, RRTNode* ))
473 {
474         if (IS_NEAR(node, this->goal_)) {
475                 if (this->goal_found_) {
476                         if (node->ccost() + this->cost(node, this->goal_) <
477                                         this->goal_->ccost()) {
478                                 RRTNode *op; // old parent
479                                 float oc; // old cumulative cost
480                                 float od; // old direct cost
481                                 op = this->goal_->parent();
482                                 oc = this->goal_->ccost();
483                                 od = this->goal_->dcost();
484                                 node->add_child(this->goal_,
485                                                 this->cost(node, this->goal_));
486                                 if (this->collide(node, this->goal_)) {
487                                         node->children().pop_back();
488                                         this->goal_->parent(op);
489                                         this->goal_->ccost(oc);
490                                         this->goal_->dcost(od);
491                                 } else {
492                                         op->rem_child(this->goal_);
493                                         return true;
494                                 }
495                         } else {
496                                 return false;
497                         }
498                 } else {
499                         node->add_child(
500                                         this->goal_,
501                                         this->cost(node, this->goal_));
502                         if (this->collide(node, this->goal_)) {
503                                 node->children().pop_back();
504                                 this->goal_->remove_parent();
505                                 return false;
506                         }
507                         this->goal_found_ = true;
508                         // Update ccost of goal's parents
509                         if (this->goals().size() > 0) {
510                                 RRTNode *ch = this->goals().back();
511                                 RRTNode *pn = this->goals().back()->parent();
512                                 while (pn) {
513                                         pn->ccost(
514                                                 ch->ccost()
515                                                 - this->cost(pn, ch)
516                                         );
517                                         ch = pn;
518                                         pn = pn->parent();
519                                 }
520                         }
521                         return true;
522                 }
523         }
524         return false;
525 }
526
527 bool RRTBase::goal_found(
528         RRTNode *node,
529         RRTNode *goal
530 )
531 {
532         if (IS_NEAR(node, goal)) {
533                 if (this->goal_found_) {
534                         if (
535                                 goal->ccost() != -1
536                                 && node->ccost() + this->cost(node, goal)
537                                 < goal->ccost()
538                         ) {
539                                 RRTNode *op; // old parent
540                                 float oc; // old cumulative cost
541                                 float od; // old direct cost
542                                 op = goal->parent();
543                                 oc = goal->ccost();
544                                 od = goal->dcost();
545                                 node->add_child(goal,
546                                                 this->cost(node, goal));
547                                 if (this->collide(node, goal)) {
548                                         node->children().pop_back();
549                                         goal->parent(op);
550                                         goal->ccost(oc);
551                                         goal->dcost(od);
552                                 } else {
553                                         op->rem_child(goal);
554                                         return true;
555                                 }
556                         } else {
557                                 return false;
558                         }
559                 } else {
560                         node->add_child(
561                                 goal,
562                                 this->cost(node, goal)
563                         );
564                         if (this->collide(node, goal)) {
565                                 node->children().pop_back();
566                                 goal->remove_parent();
567                                 return false;
568                         }
569                         this->goal_found_ = true;
570                         // Update ccost of goal's children
571                         goal->update_ccost();
572                         // Update ccost of goals
573                         for (auto g: this->goals()) {
574                                 if (g == goal)
575                                         break;
576                                 g->ccost(-1);
577                         }
578                         return true;
579                 }
580         }
581         return false;
582 }
583
584 bool RRTBase::collide(RRTNode *init, RRTNode *goal)
585 {
586         std::vector<RRTEdge *> edges;
587         RRTNode *tmp = goal;
588         volatile bool col = false;
589         unsigned int i;
590         while (tmp != init) {
591                 BicycleCar bc(tmp->x(), tmp->y(), tmp->h());
592                 std::vector<RRTEdge *> bcframe = bc.frame();
593                 #pragma omp parallel for reduction(|: col)
594                 for (i = 0; i < (*this->cobstacles_).size(); i++) {
595                         if ((*this->cobstacles_)[i].collide(tmp)) {
596                                 col = true;
597                         }
598                         for (auto &e: bcframe) {
599                                 if ((*this->cobstacles_)[i].collide(e)) {
600                                         col = true;
601                                 }
602                         }
603                 }
604                 if (col) {
605                         for (auto e: bcframe) {
606                                 delete e->init();
607                                 delete e->goal();
608                                 delete e;
609                         }
610                         for (auto e: edges) {
611                                 delete e;
612                         }
613                         return true;
614                 }
615                 #pragma omp parallel for reduction(|: col)
616                 for (i = 0; i < (*this->sobstacles_).size(); i++) {
617                         for (auto &e: bcframe) {
618                                 if ((*this->sobstacles_)[i].collide(e)) {
619                                         col = true;
620                                 }
621                         }
622                 }
623                 if (col) {
624                         for (auto e: bcframe) {
625                                 delete e->init();
626                                 delete e->goal();
627                                 delete e;
628                         }
629                         for (auto e: edges) {
630                                 delete e;
631                         }
632                         return true;
633                 }
634                 if (!tmp->parent()) {
635                         break;
636                 }
637                 edges.push_back(new RRTEdge(tmp, tmp->parent()));
638                 tmp = tmp->parent();
639                 for (auto e: bcframe) {
640                         delete e->init();
641                         delete e->goal();
642                         delete e;
643                 }
644         }
645         for (auto &e: edges) {
646                 #pragma omp parallel for reduction(|: col)
647                 for (i = 0; i < (*this->cobstacles_).size(); i++) {
648                         if ((*this->cobstacles_)[i].collide(e)) {
649                                 col = true;
650                         }
651                 }
652                 if (col) {
653                         for (auto e: edges) {
654                                 delete e;
655                         }
656                         return true;
657                 }
658                 #pragma omp parallel for reduction(|: col)
659                 for (i = 0; i < (*this->sobstacles_).size(); i++) {
660                         if ((*this->sobstacles_)[i].collide(e)) {
661                                 col = true;
662                         }
663                 }
664                 if (col) {
665                         for (auto e: edges) {
666                                 delete e;
667                         }
668                         return true;
669                 }
670         }
671         for (auto e: edges) {
672                 delete e;
673         }
674         return false;
675 }
676
677 class RRTNodeDijkstra {
678         public:
679                 RRTNodeDijkstra(int i):
680                         ni(i),
681                         pi(0),
682                         c(9999),
683                         v(false)
684                 {};
685                 RRTNodeDijkstra(int i, float c):
686                         ni(i),
687                         pi(0),
688                         c(c),
689                         v(false)
690                 {};
691                 RRTNodeDijkstra(int i, int p, float c):
692                         ni(i),
693                         pi(p),
694                         c(c),
695                         v(false)
696                 {};
697                 unsigned int ni;
698                 unsigned int pi;
699                 float c;
700                 bool v;
701                 bool vi()
702                 {
703                         if (this->v)
704                                 return true;
705                         this->v = true;
706                         return false;
707                 };
708 };
709
710 class RRTNodeDijkstraComparator {
711         public:
712                 int operator() (
713                                 const RRTNodeDijkstra& n1,
714                                 const RRTNodeDijkstra& n2)
715                 {
716                         return n1.c > n2.c;
717                 }
718 };
719
720 bool RRTBase::optp_dijkstra(
721                 std::vector<RRTNode *> &cusps,
722                 std::vector<int> &npi)
723 {
724         std::vector<RRTNodeDijkstra> dnodes;
725         for (unsigned int i = 0; i < cusps.size(); i++)
726                 if (i > 0)
727                         dnodes.push_back(RRTNodeDijkstra(
728                                                 i,
729                                                 i - 1,
730                                                 cusps[i]->ccost()));
731                 else
732                         dnodes.push_back(RRTNodeDijkstra(
733                                                 i,
734                                                 cusps[i]->ccost()));
735         dnodes[0].vi();
736         std::priority_queue<
737                 RRTNodeDijkstra,
738                 std::vector<RRTNodeDijkstra>,
739                 RRTNodeDijkstraComparator> pq;
740         RRTNodeDijkstra tmp = dnodes[0];
741         pq.push(tmp);
742         float ch_cost = 9999;
743         std::vector<RRTNode *> steered;
744         while (!pq.empty()) {
745                 tmp = pq.top();
746                 pq.pop();
747                 for (unsigned int i = tmp.ni + 1; i < cusps.size(); i++) {
748                         ch_cost = dnodes[tmp.ni].c +
749                                 this->cost(cusps[tmp.ni], cusps[i]);
750                         steered = this->steer(cusps[tmp.ni], cusps[i]);
751                         for (unsigned int j = 0; j < steered.size() - 1; j++)
752                                 steered[j]->add_child(steered[j + 1], 1);
753                         if (this->collide(
754                                         steered[0],
755                                         steered[steered.size() - 1])) {
756                                 for (auto n: steered)
757                                         delete n;
758                                 continue;
759                         }
760                         if (ch_cost < dnodes[i].c) {
761                                 dnodes[i].c = ch_cost;
762                                 dnodes[i].pi = tmp.ni;
763                                 if (!dnodes[i].vi())
764                                         pq.push(dnodes[i]);
765                         }
766                         for (auto n: steered)
767                                 delete n;
768                 }
769         }
770         unsigned int tmpi = 0;
771         for (auto n: dnodes) {
772                 if (n.v && n.ni > tmpi)
773                         tmpi = n.ni;
774         }
775         while (tmpi > 0) {
776                 npi.push_back(tmpi);
777                 tmpi = dnodes[tmpi].pi;
778         }
779         npi.push_back(tmpi);
780         std::reverse(npi.begin(), npi.end());
781         return true;
782 }
783
784 bool RRTBase::optp_rrp(
785                 std::vector<RRTNode *> &cusps,
786                 std::vector<int> &npi)
787 {
788         std::vector<RRTNode *> steered;
789         std::vector<int> candidates;
790         RRTNode *x_j = nullptr;
791         RRTNode *x_i = nullptr;
792         int j = cusps.size() - 1;
793         int i_min = 0;
794         float c_min = 0;
795         float cost = 0;
796         float dx = 0;
797         float dy = 0;
798         float ed = 0;
799         float th_i = 0;
800         float th_j = 0;
801         while (j > 0) {
802                 npi.push_back(j);
803                 steered.clear();
804                 candidates.clear();
805                 x_j = cusps[j];
806                 for (int i = 0; i < j; i++) {
807                         steered = this->steer(cusps[i], x_j);
808                         for (unsigned int k = 0; k < steered.size() - 1; k++)
809                                 steered[k]->add_child(steered[k + 1], 1);
810                         if (!this->collide(
811                                         steered[0],
812                                         steered[steered.size() - 1]))
813                                 candidates.push_back(i);
814                 }
815                 if (candidates.size() <= 0)
816                         return false;
817                 i_min = candidates[0];
818                 x_i = cusps[i_min];
819                 c_min = 9999;
820                 for (auto c: candidates) {
821                         x_i = cusps[c];
822                         dx = x_j->x() - x_i->x();
823                         dy = x_j->y() - x_i->y();
824                         ed = EDIST(x_i, x_j);
825                         th_i = (cos(x_i->h()) * dx + sin(x_i->h()) * dy) / ed;
826                         th_j = (cos(x_j->h()) * dx + sin(x_j->h()) * dy) / ed;
827                         cost = th_i + th_j;
828                         if (cost < c_min) {
829                                 i_min = c;
830                                 c_min = cost;
831                         }
832                 }
833                 j = i_min;
834
835         }
836         npi.push_back(j);
837         std::reverse(npi.begin(), npi.end());
838         return true;
839 }
840
841 bool RRTBase::optp_smart(
842                 std::vector<RRTNode *> &cusps,
843                 std::vector<int> &npi)
844 {
845         std::vector<RRTNode *> steered;
846         int li = cusps.size() - 1;
847         int ai = li - 1;
848         npi.push_back(li);
849         while (ai > 1) {
850                 steered = this->steer(cusps[ai - 1], cusps[li]);
851                 for (unsigned int j = 0; j < steered.size() - 1; j++)
852                         steered[j]->add_child(steered[j + 1], 1);
853                 if (this->collide(steered[0], steered[steered.size() - 1])) {
854                         npi.push_back(ai);
855                         li = ai;
856                 }
857                 ai--;
858                 for (auto n: steered)
859                         delete n;
860         }
861         npi.push_back(0);
862         std::reverse(npi.begin(), npi.end());
863         return true;
864 }
865
866 bool RRTBase::opt_path()
867 {
868         if (this->tlog().size() == 0)
869                 return false;
870         float oc = this->tlog().back().front()->ccost();
871         std::vector<RRTNode *> tmp_cusps;
872         for (auto n: this->tlog().back()) {
873                 if (sgn(n->s()) == 0) {
874                         tmp_cusps.push_back(n);
875                 } else if (n->parent() &&
876                                 sgn(n->s()) != sgn(n->parent()->s())) {
877                         tmp_cusps.push_back(n);
878                         tmp_cusps.push_back(n->parent());
879                 }
880                 //tmp_cusps.push_back(n);
881         }
882         if (tmp_cusps.size() < 2)
883                 return false;
884         std::vector<RRTNode *> cusps;
885         for (unsigned int i = 0; i < tmp_cusps.size(); i++) {
886                 if (tmp_cusps[i] != tmp_cusps[(i + 1) % tmp_cusps.size()])
887                         cusps.push_back(tmp_cusps[i]);
888         }
889         std::reverse(cusps.begin(), cusps.end());
890         std::vector<int> npi; // new path indexes
891         if (!this->optp_dijkstra(cusps, npi))
892                 return false;
893         RRTNode *pn = cusps[npi[0]];
894         RRTNode *tmp = nullptr;
895         bool en_add = true;
896         for (unsigned int i = 0; i < npi.size() - 1; i++) {
897                 pn = cusps[npi[i]];
898                 for (auto ns: this->steer(cusps[npi[i]], cusps[npi[i + 1]])) {
899                         if (!en_add) {
900                                 delete ns;
901                         } else if (IS_NEAR(cusps[npi[i]], ns)) {
902                                 tmp = ns;
903                                 while (tmp && tmp != cusps[npi[i]]) {
904                                         pn = tmp->parent();
905                                         delete tmp;
906                                         tmp = pn;
907                                 }
908                                 pn = cusps[npi[i]];
909                         } else if (IS_NEAR(ns, cusps[npi[i + 1]])) {
910                                 delete ns;
911                                 cusps[npi[i + 1]]->parent()->rem_child(
912                                                 cusps[npi[i + 1]]);
913                                 pn->add_child(
914                                         cusps[npi[i + 1]],
915                                         this->cost(pn, cusps[npi[i + 1]]));
916                                 en_add = false;
917                         } else if (IS_NEAR(pn, ns)) {
918                                 delete ns;
919                         } else {
920                                 this->nodes().push_back(ns);
921                                 this->add_iy(ns);
922                                 this->add_ixy(ns);
923                                 pn->add_child(ns, this->cost(pn, ns));
924                                 pn = ns;
925                         }
926                 }
927         }
928         this->root()->update_ccost();
929         if (this->tlog().back().front()->ccost() < oc)
930                 return true;
931         return false;
932 }
933
934 bool RRTBase::rebase(RRTNode *nr)
935 {
936         if (!nr || this->goal_ == nr || this->root_ == nr)
937                 return false;
938         std::vector<RRTNode *> s; // DFS stack
939         RRTNode *tmp;
940         unsigned int i = 0;
941         unsigned int to_del = 0;
942         int iy = 0;
943         s.push_back(this->root_);
944         while (s.size() > 0) {
945                 tmp = s.back();
946                 s.pop_back();
947                 for (auto ch: tmp->children()) {
948                         if (ch != nr)
949                                 s.push_back(ch);
950                 }
951                 to_del = this->nodes_.size();
952                 #pragma omp parallel for reduction(min: to_del)
953                 for (i = 0; i < this->nodes_.size(); i++) {
954                         if (this->nodes_[i] == tmp)
955                                 to_del = i;
956                 }
957                 if (to_del < this->nodes_.size())
958                         this->nodes_.erase(this->nodes_.begin() + to_del);
959                 iy = IYI(tmp->y());
960                 to_del = this->iy_[iy].size();
961                 #pragma omp parallel  for reduction(min: to_del)
962                 for (i = 0; i < this->iy_[iy].size(); i++) {
963                         if (this->iy_[iy][i] == tmp)
964                                 to_del = i;
965                 }
966                 if (to_del < this->iy_[iy].size())
967                         this->iy_[iy].erase(this->iy_[iy].begin() + to_del);
968                 this->dnodes().push_back(tmp);
969         }
970         this->root_ = nr;
971         this->root_->remove_parent();
972         return true;
973 }
974
975 std::vector<RRTNode *> RRTBase::findt()
976 {
977         return this->findt(this->goal_);
978 }
979
980 std::vector<RRTNode *> RRTBase::findt(RRTNode *n)
981 {
982         std::vector<RRTNode *> nodes;
983         if (!n || !n->parent())
984                 return nodes;
985         while (n) {
986                 nodes.push_back(n);
987                 n = n->parent();
988         }
989         return nodes;
990 }
991
992 // RRT Framework
993 RRTNode *RRTBase::sample()
994 {
995         if (this->useSamplingInfo_ && this->nodes().size() % 2 == 0) {
996                 float x = static_cast<float>(rand());
997                 x /= static_cast<float>(RAND_MAX / this->samplingInfo_.x);
998                 x -= this->samplingInfo_.x / 2;
999                 x += this->samplingInfo_.x0;
1000                 float y = static_cast<float>(rand());
1001                 y /= static_cast<float>(RAND_MAX / this->samplingInfo_.y);
1002                 y -= this->samplingInfo_.y / 2;
1003                 y += this->samplingInfo_.y0;
1004                 float h = static_cast<float>(rand());
1005                 h /= static_cast<float>(RAND_MAX / this->samplingInfo_.h);
1006                 h -= this->samplingInfo_.h / 2;
1007                 h += this->samplingInfo_.h0;
1008                 return new RRTNode(x, y, h);
1009         } else {
1010                 float x = this->ndx_(this->gen_);
1011                 float y = this->ndy_(this->gen_);
1012                 float h = this->ndh_(this->gen_);
1013                 return new RRTNode(x, y, h);
1014         }
1015 }
1016
1017 float RRTBase::cost(RRTNode *init, RRTNode *goal)
1018 {
1019         return co2(init, goal);
1020 }
1021
1022 RRTNode *RRTBase::nn(RRTNode *rs)
1023 {
1024         return nn4(this->iy_, rs, nullptr);
1025         //return nn3(this->iy_, rs, nullptr);
1026 }
1027
1028 std::vector<RRTNode *> RRTBase::nv(RRTNode *node, float dist)
1029 {
1030         std::vector<RRTNode *> nvs;
1031         unsigned int iy = IYI(node->y());
1032         unsigned int iy_dist = floor(dist / IYSTEP) + 1;
1033         unsigned int i = 0; // vector index
1034         unsigned int j = 0; // array index
1035         unsigned int jmin = 0; // minimal j index
1036         unsigned int jmax = 0; // maximal j index
1037         jmin = iy - iy_dist;
1038         jmin = (jmin > 0) ? jmin : 0;
1039         jmax = iy + iy_dist + 1;
1040         jmax = (jmax < IYSIZE) ? jmax : IYSIZE;
1041         #pragma omp parallel for reduction(merge: nvs)
1042         for (j = jmin; j < jmax; j++) {
1043                 #pragma omp parallel for reduction(merge: nvs)
1044                 for (i = 0; i < this->iy_[j].size(); i++) {
1045                         if (this->cost(this->iy_[j][i], node) < dist) {
1046                                 nvs.push_back(this->iy_[j][i]);
1047                         }
1048                 }
1049         }
1050         return nvs;
1051 }
1052
1053 std::vector<RRTNode *> RRTBase::steer(RRTNode *init, RRTNode *goal)
1054 {
1055         return st3(init, goal);
1056 }
1057
1058 std::vector<RRTNode *> RRTBase::steer(RRTNode *init, RRTNode *goal, float step)
1059 {
1060         return st3(init, goal, step);
1061 }